Search Insert Position

Find the index of target in a sorted array, or the index where it would be inserted to maintain order.

Easy
Time O(log n) Space O(1)
LeetCode
2 min read
binary-search

Problem#

Sorted array nums. Return the index of target if present, otherwise the index where it would be inserted.

Examples#

  • nums = [1,3,5,6], target = 52
  • nums = [1,3,5,6], target = 21

Constraints#

  • 1 <= n <= 10^4.

Approach#

Lower-bound binary search.

Solution#

Search Insert Position
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int lo = 0, hi = nums.size();
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] < target) lo = mid + 1;
else hi = mid;
}
return lo;
}
};

Editorial#

Standard lower_bound template: hi = n (exclusive upper bound), lo < hi, lo = mid + 1 if smaller, hi = mid if at-least. Final lo is the first index ≥ target — the insert position.

Complexity#

  • Time: O(log n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.