DSA and coding Level 1 This level · 8 of 19
Easy dsa binary-search

Search Insert Position

The 30 second answer

I need the index of the target, or the index where it would be inserted to keep the array sorted. That is a lower bound: the first index whose value is greater than or equal to the target. I use a half-open range and move lo up when mid is strictly less than the target.

Could you say this in an interview?

Problem Given a sorted array of distinct integers and a target, return the index of the target if it is present, otherwise the index where it would be inserted in order. Original: LeetCode 35: Search Insert Position.

Understanding the prompt The answer is always in 0 to n inclusive: n means insert at the end. Distinct values mean you do not have to choose among equals, but the same lower-bound loop is the one you will reuse when duplicates appear.

Pattern recognition Boundary binary search, also called lower bound: the first index that satisfies a predicate, here nums[i] >= target.

Brute force A linear scan until you find a value >= target: O(n).

Optimal lo = 0, hi = n, half-open. While lo < hi, mid = lo + (hi - lo) / 2. If nums[mid] < target, lo = mid + 1, else hi = mid. When the loop ends, lo is the insertion point, and also the index of the target when it is present.

Alternatives The inclusive-bounds version has more off-by-one ways to go wrong. Stick to a clearly named lower-bound helper and reuse it, including in Find First and Last Position.

Java solution

public class SearchInsertPosition {
    static int searchInsert(int[] nums, int target) {
        int lo = 0, hi = nums.length; // first index with nums[i] >= target
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;
            if (nums[mid] < target) lo = mid + 1;
            else hi = mid;
        }
        return lo;
    }

    public static void main(String[] args) {
        System.out.println(searchInsert(new int[] {1, 3, 5, 6}, 5)); // 2
        System.out.println(searchInsert(new int[] {1, 3, 5, 6}, 2)); // 1
        System.out.println(searchInsert(new int[] {1, 3, 5, 6}, 7)); // 4
        System.out.println(searchInsert(new int[] {1, 3, 5, 6}, 0)); // 0
    }
}

Complexity O(log n) time, O(1) extra space.

Edge cases

  • The target is already in the array, as in [1,3,5,6] with 5, which returns 2.
  • The target belongs in the middle, at the start, or at the end, as with 2, 0 and 7 on the same array.

Follow-ups

  • First and last position of a value: lower bound of target and lower bound of target + 1, minus one.
  • The upper bound, first index with nums[i] > target, is the same loop with a <= test.

Tests [1,3,5,6] with 5 returns 2, with 2 returns 1, with 7 returns 4, and with 0 returns 0.

How to say it in the interview "I want the first index whose value is at least the target, which is also the insertion point when the target is missing. I search a half-open range and move lo up only when mid is strictly less than the target. Logarithmic time."

Sources (1)
  1. LeetCode 35: Search Insert Positionleetcode.com
Previous
Next