KatInterview

35. Search Insert Position

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem requires us to find the index of a target value in a sorted array of distinct integers. If the target is not found, we need to return the index where it would be inserted to maintain the sorted order. The crucial constraint is to achieve this with an O(log n) runtime complexity, which strongly suggests using a binary search algorithm.

Solution

Search Insert Position in Python

class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        left, right = 0, len(nums)

        # The loop is designed to find the first index 'i' where nums[i] >= target.
        # This is also known as finding the lower bound.
        # The search space is the half-open interval [left, right).
        while left < right:
            # Calculate mid point.
            mid = left + (right - left) // 2

            if nums[mid] < target:
                # If nums[mid] is smaller than the target, the insertion point must be
                # to the right of mid. So we narrow the search space to [mid + 1, right).
                left = mid + 1
            else:  # nums[mid] >= target
                # If nums[mid] is greater than or equal to the target, mid could be
                # the insertion point, or there might be one to its left.
                # So we narrow the search space to [left, mid).
                right = mid

        # When the loop terminates, left == right, and this is our insertion point.
        return left

Search Insert Position in Java

class Solution {
    public int searchInsert(int[] nums, int target) {
        int left = 0;
        // The length of the array is the potential insertion point
        // if the target is larger than all elements.
        int right = nums.length;

        // The loop is designed to find the first index 'i' where nums[i] >= target.
        // This is also known as finding the lower bound.
        // The search space is the half-open interval [left, right).
        while (left < right) {
            // Calculate mid point to prevent potential integer overflow.
            int mid = left + (right - left) / 2;

            if (nums[mid] < target) {
                // If nums[mid] is smaller than the target, the insertion point must be
                // to the right of mid. So we narrow the search space to [mid + 1, right).
                left = mid + 1;
            } else { // nums[mid] >= target
                // If nums[mid] is greater than or equal to the target, mid could be
                // the insertion point, or there might be one to its left.
                // So we narrow the search space to [left, mid).
                right = mid;
            }
        }

        // When the loop terminates, left == right, and this is our insertion point.
        return left;
    }
}

Search Insert Position in C++

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int left = 0;
        // The size of the array is the potential insertion point 
        // if the target is larger than all elements.
        int right = nums.size();

        // The loop is designed to find the first index 'i' where nums[i] >= target.
        // This is also known as finding the lower bound.
        // The search space is the half-open interval [left, right).
        while (left < right) {
            // Calculate mid point to prevent potential integer overflow.
            int mid = left + (right - left) / 2;

            if (nums[mid] < target) {
                // If nums[mid] is smaller than the target, the insertion point must be
                // to the right of mid. So we narrow the search space to [mid + 1, right).
                left = mid + 1;
            } else { // nums[mid] >= target
                // If nums[mid] is greater than or equal to the target, mid could be
                // the insertion point, or there might be one to its left.
                // So we narrow the search space to [left, mid).
                right = mid;
            }
        }

        // When the loop terminates, left == right, and this is our insertion point.
        return left;
    }
};

Search Insert Position in TypeScript

function searchInsert(nums: number[], target: number): number {
    let left = 0;
    // The length of the array is the potential insertion point
    // if the target is larger than all elements.
    let right = nums.length;

    // The loop is designed to find the first index 'i' where nums[i] >= target.
    // This is also known as finding the lower bound.
    // The search space is the half-open interval [left, right).
    while (left < right) {
        // Calculate mid point, using Math.floor for integer division.
        let mid = left + Math.floor((right - left) / 2);

        if (nums[mid] < target) {
            // If nums[mid] is smaller than the target, the insertion point must be
            // to the right of mid. So we narrow the search space to [mid + 1, right).
            left = mid + 1;
        } else { // nums[mid] >= target
            // If nums[mid] is greater than or equal to the target, mid could be
            // the insertion point, or there might be one to its left.
            // So we narrow the search space to [left, mid).
            right = mid;
        }
    }

    // When the loop terminates, left == right, and this is our insertion point.
    return left;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.