EasyBinary Search
Search Insert Position
Find position to insert target
Solution Approach
Binary search to find target or insertion position. Return index where target should be.
Implementation
def searchInsert(nums, target):
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return leftComplexity Analysis
Time Complexity
O(log n)Space Complexity
O(1)Complexity
Time:O(log n)
Space:O(1)
Asked at
GoogleFacebook