Algo-Sim › Binary Search

Search Insert Position

Easy · Binary Search · step through it in Java, Python and C++ on your own input

Lower bound with a half-open [lo, hi) range: the first index whose value is ≥ target, which is also where target would be inserted.

Problem

The array nums holds distinct integers in increasing order. Return the index of target if it is present; otherwise return the index where it would be inserted to keep the array sorted. The algorithm must run in O(log n) time.

Constraints

Edge cases to test

Follow-up questions

How does this relate to library calls?
It is bisect_left in Python, lower_bound in C++, and Arrays.binarySearch with −(insertion point) − 1 in Java.
What changes for the last position instead of the first?
Use upper_bound (first value > target) and step back one: the same O(log n) loop with <= in the comparison.

Solution

Java

public int searchInsert(int[] nums, int target) {
    int lo = 0, hi = nums.length;
    while (lo < hi) {
        int mid = lo + (hi - lo) / 2;
        if (nums[mid] < target) lo = mid + 1;
        else hi = mid;
    }
    return lo;
}

Python

def search_insert(nums, target):
    lo, hi = 0, len(nums)
    while lo < hi:
        mid = lo + (hi - lo) // 2
        if nums[mid] < target: lo = mid + 1
        else: hi = mid
    return lo

C++

#include <bits/stdc++.h>
using namespace std;

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;
    }
};

More Binary Search problems