Skip to content

Link to Question

EASY

Search Insert Position

Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You must write an algorithm with O(log n) runtime complexity.

Example

Input:

nums = [1,3,5,6], target = 5

Output:

2

Explanation:
5 is found at index 2.


Constraints

  • 1 ≤ nums.length ≤ 10⁴
  • -10⁴ ≤ nums[i] ≤ 10⁴
  • nums contains distinct values sorted in ascending order.
  • -10⁴ ≤ target ≤ 10⁴

  • Time Complexity: O(log n)
  • Space Complexity: O(1)
C++
class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int low = 0, high = nums.size()-1;
        while(low < high) {
            int mid = (low + high) / 2;
            if (nums[mid] >= target) high = mid;
            else low = mid + 1;
        }

        return nums[low] >= target? low : low + 1;
    }
};