35 Search Insert Position

Given a sorted array 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 may assume no duplicates in the array.

Here are few examples.

[1,3,5,6], 5 -> 2
[1,3,5,6], 2 -> 1
[1,3,5,6], 7 -> 4
[1,3,5,6], 0 -> 0
int searchInsert(vector<int>& nums, int target) {
    if (nums.size() == 0) return 0;

    for (int i = 0; i < nums.size(); i++) {
        if (nums.at(i) >= target) {
            return i;
        }
    }
    return nums.size();
}

int main() {
    vector<int> nums = { 1, 3, 5, 6 };
    cout << searchInsert(nums, 5) << endl;
    pause();

    cout << searchInsert(nums, 2) << endl;
    pause();

    cout << searchInsert(nums, 7) << endl;
    pause();

    cout << searchInsert(nums, 0) << endl;
    pause();

}

Implementation 2: O(logn)

  • Use binary search to find the element.

  • But if binary search fails to find the element, then check to see whether the element it has failed on is greater than the target value. If it is, then it is an indication that the index is at the correct location.

  • Otherwise, it is the next.

template<typename T> 
int binary_search(vector<T> &nums, int low, int high, T key, int prev_i) {
    if (high < low) {
        if (nums[prev_i] > key)
            return prev_i;
        else return prev_i + 1;
    }

    int median = low + ((high - low) / 2);

    if (nums.at(median) == key)
        return median;
    else if (nums.at(median) > key) 
        return binary_search(nums, low, median - 1, key, median);
    return binary_search(nums, median + 1 , high, key, median);
}


int searchInsert(vector<int>& nums, int target) {
    return binary_search(nums, 0, nums.size() - 1, target, 0);
}


int main()
{    
    cout << searchInsert(vector<int>() = {1,3,5,6}, 5) << endl; // 2
    cout << searchInsert(vector<int>() = {1,3,5,6}, 2) << endl; // 1
    cout << searchInsert(vector<int>() = {1,3,5,6}, 7) << endl; // 4
    cout << searchInsert(vector<int>() = {1,3,5,6}, 0) << endl; // 0
    cout << searchInsert(vector<int>() = {1,3}, 2) << endl; // 1
    cout << searchInsert(vector<int>() = {3,5,7,9,10}, 8) << endl; // 3
}

Last updated