Leetcode: Search Insert Position
2 min readDec 25, 2016
Given a sorted list and a value, we need to find the index where it should be inserted or return the index at which it is already present. Searching in a sorted list should always be done using binary search. The steps are listed below
- Find the middle element of the list
- If value matches with target then return the index
- If value is greater than target, we need to search the left half
- Otherwise we need to search the right half
To code the above logic
- Use pointers low and high to define the range of search
- Initialize low with 0 and high with length of array
- Initialize mid with average of low and high
- To search in left half move high pointer to mid and recalculate mid
- To search in right half move the left pointer to mid and recalculate mid
- Continue till mid equals low at which point further iterations will keep on pointing mid to low
Remarks
- O(log n) time complexity for using divide and conquer technique
- O(1) space complexity as only 3 additional variables are used
- Integer overflow is prevented by using the expression (high-low) instead of (high+low). This is not applicable to python as python converts int to long as per the need.
- The result of low+(high-low)/2 will never be equal to high, it can at most reach high-1. Hence we initialize high with length of list to reach the last valid index which is one less than the length of list
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
low, high = 0, len(nums)
mid = low + (high - low) / 2
while mid != low:
if nums[mid] == target:
return mid
elif nums[mid] < target:
low = mid
else:
high = mid
mid = low + (high - low) / 2
return mid if target <= nums[mid] else mid + 1
This code is useful for solving a variety of problems. You might need to change the condition at which it returns or call it multiple times.