The “Search Insert Position” problem asks us to find the index at which a given target value should be inserted into a sorted array. If the target is already present, return its current index. If not, return the index where it should be inserted to maintain the array's sorted order.
Example:
nums = [1, 3, 5, 6]
, target = 5
→ Output: 2
nums = [1, 3, 5, 6]
, target = 2
→ Output: 1
nums = [1, 3, 5, 6]
, target = 7
→ Output: 4
This problem is a common application of binary search. It appears frequently in interviews and is useful in practical scenarios like autocomplete systems, ordered data insertion, and maintaining sorted arrays in real time. Understanding how to return an insertion point makes binary search more versatile.
Since the input array is sorted, we can use binary search to find the target or determine its correct insertion index. Unlike standard binary search that returns -1 if the target is not found, here we use the final low pointer to return the insertion position.
left = 0
and right = nums.length - 1
.left <= right
:
mid = Math.floor((left + right) / 2)
.nums[mid] == target
, return mid
(target found).nums[mid] < target
, move left
to mid + 1
.nums[mid] > target
, move right
to mid - 1
.left
as the correct insertion position (either where the target exists or where it would be placed).
Input: nums = [1, 3, 5, 6]
, target = 2
Time Complexity: O(log n), where n is the number of elements in the array.
Space Complexity: O(1), since we are using constant extra space.
The “Search Insert Position” problem is a great demonstration of how binary search can be adapted beyond finding exact matches. By returning the low pointer when the search ends, we efficiently find where a value should be placed in a sorted structure — a useful pattern in many real-world systems that maintain ordered data.