Question on Leetcode - Easy
The approach taken was the binary search to find the target. I initialized two pointers, left and right at the beginning and end of the array respectfully. Then I used a while loop left < right. Then in the loop, I calculate the mid and compare it to the target. If the mid is the target, I return mid. If the mid is less than the target, I add a unit step to the left and if the mid is grater than one, I remove a unit step from the right. If the loop is exited without finding the target, it means the target will be inserted the the left and then I return the left
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
if nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return left
- Time Complexity - Olog(n) as explicitly stated in the question
- Space complexity - O(n)