Search Insert Position

Easy Binary SearchArray

Problem

Given a sorted array of distinct integers and a target, return the index if found. If not, return the index where it would be inserted to keep the array sorted. Must run in O(log n).

Example 1 Input: nums = [1,3,5,6], target = 5 Output: 2
Example 2 Input: nums = [1,3,5,6], target = 2 Output: 1
Example 3 Input: nums = [1,3,5,6], target = 7 Output: 4

Constraints

Approach — Binary Search

This is a Binary Search problem. The idea: repeatedly halve the search space, discarding the half that can't contain the answer. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: O(log n) time.

Solution code

Python

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

Java

class Solution {
    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;
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Search Insert Position interactively → ← All solutions