Search Insert Position

Updated on 23 June, 2025
Search Insert Position header image

Problem Statement

The task involves working with a sorted array of distinct integers to identify the position of a given target value. The problem is twofold; if the target value is present in the array, the function should return its index. If the target is not present in the array, the function must determine where the target would be inserted to maintain the sorted order. The core challenge is to devise an algorithm that resolves this problem with a time complexity of O(log n), suggesting the use of an efficient strategy such as binary search to minimize the number of comparisons even in large datasets.

Examples

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

  • 1 <= nums.length <= 104
  • -104 <= nums[i] <= 104
  • nums contains distinct values sorted in ascending order.
  • -104 <= target <= 104

Approach and Intuition

The most suitable approach for achieving an O(log n) runtime complexity in searching for an element within a sorted list is to employ the binary search technique. Here’s how you can intuitively think about implementing this:

  1. Initialize two pointers: one called start at the beginning of the array and another called end at the last index of the array.
  2. Enter a loop where you continually adjust the start and end pointers based on the middle element’s relationship with the target value (calculated as mid = start + (end - start) / 2):
    • If nums[mid] is equal to the target, then you have found the target’s index.
    • If nums[mid] is less than the target, adjust the start pointer to mid + 1 to search the upper half of the array.
    • If nums[mid] is greater than the target, adjust the end pointer to mid - 1 to search the lower half.
  3. This loop continues until the start pointer is greater than the end pointer. At this point, if the target has not been found, the current position of the start pointer is where the target would be inserted to maintain the order since the loop exits when start becomes greater than the position where the element would fit.

Examples provided demonstrate various scenarios:

  • In the first example, the binary search concludes the target 5 existing in the array at index 2.
  • In the second, the target 2 doesn't exist, and the algorithm identifies the correct insertion point at index 1.
  • Similarly, for a target 7 in the third example, the algorithm determines the target would be inserted at the end, yielding index 4 because it is greater than all other elements.

By adhering to this method, not only does every step halve the search space, resulting in a logarithmic time complexity, but it also guarantees the correct index position whether or not the target exists in the array.

Solutions

  • C++
  • Java
  • C
  • JavaScript
  • Python
cpp
class Solution {
public:
    int findPosition(vector<int>& data, int searchValue) {
        int mid, start = 0, end = data.size() - 1;
        while (start <= end) {
            mid = start + (end - start) / 2;
            if (data[mid] == searchValue) return mid;
            if (searchValue < data[mid])
                end = mid - 1;
            else
                start = mid + 1;
        }
        return start;
    }
};

The provided C++ solution focuses on finding the insert position for a given value within a sorted array using the binary search technique. This efficient algorithm locates the specific index where a value should be inserted in order to maintain the array's sorted order, even if the value is not originally present in the array.

Follow these steps for this binary search implementation:

  1. Initialize two pointers, start set to 0 and end set to the last index of the array.
  2. Enter a while loop, which continues until start exceeds end.
  3. Calculate the mid index to split the array and compare the searchValue against the element at mid.
  4. If the searchValue is equal to the element at mid, immediately return mid as their values match.
  5. If the searchValue is lesser than the element at mid, adjust the end pointer to mid - 1 to search the left subarray.
  6. If the searchValue is greater, shift the start pointer to mid + 1 to focus on the right subarray.
  7. Once the loop ends, return start. This position represents where the searchValue would fit into the sorted array.

This method effectively provides the correct index for insertion or confirms the existence of a value within logarithmic time complexity.

java
class Solution {
    public int findInsertPosition(int[] array, int key) {
        int mid, start = 0, end = array.length - 1;
        while (start <= end) {
            mid = start + (end - start) / 2;
            if (array[mid] == key) return mid;
            if (key < array[mid]) end = mid - 1;
            else start = mid + 1;
        }
        return start;
    }
}

The solution provided is for determining the appropriate index at which to insert a given key in a sorted array, ensuring the array remains in order. Written in Java, the method findInsertPosition employs a binary search algorithm to efficiently locate either the position of the key or the index where it should be inserted if it's not already in the array.

Follow these steps to comprehend the method's execution:

  1. Initialize start to 0 and end to the length of the array minus one.
  2. Enter a while loop which continues until start is greater than end.
  3. Calculate the middle index, mid, using the formula start + (end - start) / 2.
  4. If the element at mid is equal to key, return mid as the key is already in the array.
  5. If the key is less than the element at mid, adjust the end to mid - 1.
  6. Otherwise, adjust the start to mid + 1 to continue searching in the latter half of the array.
  7. If the loop concludes without finding the key, return start. This is the index where key should be inserted to maintain the order of the array.

This implementation provides an optimal solution with a time complexity of O(log n), leveraging the binary search strategy efficiently for sorted arrays.

c
int findPosition(int* array, int length, int searchVal) {
    int mid, start = 0, end = length - 1;
    while (start <= end) {
        mid = start + (end - start) / 2;
        if (array[mid] == searchVal) return mid;
        if (searchVal < array[mid])
            end = mid - 1;
        else
            start = mid + 1;
    }
    return start;
}

The provided C function findPosition implements an efficient method to determine the index at which a given value should be inserted into a sorted array such that the array still maintains its sorted order. This method uses the binary search technique to locate either the exact match of the search value or the appropriate insertion point if the value doesn't exist in the array.

Here's a breakdown of what the function does:

  • It receives three parameters:

    • int* array - a pointer to the first element of the sorted integer array.
    • int length - the number of elements in the array.
    • int searchVal - the value to search for or insert.
  • The algorithm initializes two pointers, start and end, which define the current segment of the array being searched. start is set to 0, and end is set to length - 1.

  • Inside a while loop, as long as start is less than or equal to end:

    • Calculate the middle index mid.
    • If the middle element array[mid] matches searchVal, return mid, indicating the exact location of searchVal.
    • If searchVal is less than array[mid], adjust the end pointer to check the left sub-array.
    • Otherwise, adjust the start pointer to explore the right sub-array.
  • If the loop exits without finding searchVal, return start. This is the index where searchVal should be inserted to maintain the sorted order.

This function not only locates a value within a sorted array but also provides a convenient mechanism to find the correct insertion position for maintaining order. This utility can be significantly beneficial in scenarios where maintaining a sorted array is critical, such as in certain database operations or list management activities where order must be preserved dynamically.

js
var findInsertPosition = function (arr, value) {
    let midIndex,
        start = 0,
        end = arr.length - 1;
    while (start <= end) {
        midIndex = start + Math.floor((end - start) / 2);
        if (arr[midIndex] == value) return midIndex;
        if (value < arr[midIndex]) end = midIndex - 1;
        else start = midIndex + 1;
    }
    return start;
};

The solution for the "Search Insert Position" problem consists of implementing a binary search algorithm in JavaScript to determine the index at which a given value should be inserted into a sorted array. This approach efficiently locates either the position of an existing element or the appropriate insert position for a new element in logarithmic time complexity, O(log n).

Here’s how the provided JavaScript function achieves the solution:

  • Initialize two pointers, start and end, to represent the current bounds of the subarray being searched. start is set to 0, and end is set to the last index of the array.

  • Use a while loop to continue searching as long as start is less than or equal to end. Inside the loop:

  • Calculate the middle index (midIndex) by averaging the start and end indices, adjusted for integer division.

  • Compare the middle element of the subarray (arr[midIndex]) with the value to be inserted:

    • If they are equal, return midIndex, indicating the value already exists in the array at this position.
    • If value is less than arr[midIndex], adjust the end pointer to midIndex - 1 to search the left subarray.
    • If value is greater, adjust the start pointer to midIndex + 1 to search the right subarray.
  • If the loop concludes without finding the value, return start. This is the point where value would be inserted to maintain sorted order, as start will have moved to the correct insert position.

This implementation efficiently ensures that the array remains sorted after the insertion and finds the required position with minimal computations.

python
class Solution:
    def findInsertPosition(self, numbers: List[int], value: int) -> int:
        low, high = 0, len(numbers) - 1
        while low <= high:
            mid = (low + high) // 2
            if numbers[mid] == value:
                return mid
            if value < numbers[mid]:
                high = mid - 1
            else:
                low = mid + 1
        return low

The provided Python code offers an efficient solution to the problem of finding the insertion position of a value in a sorted list of integers. The function findInsertPosition uses the binary search technique to quickly locate where the given value should be inserted in the numbers list to maintain its order.

Follow these steps to understand the code's execution:

  1. Initialize two pointers, low and high, to the beginning and end of the list, respectively.
  2. Enter a while loop that continues until low exceeds high.
  3. Calculate the middle index mid by averaging low and high.
  4. Compare the list element at the mid index with the target value.
    • If they match, return mid as the insertion index.
    • If the target value is less, adjust high to mid - 1.
    • Otherwise, adjust low to mid + 1.
  5. If the loop exits without finding the value, return low. This will be the correct insert position when value is not found in the list.

This algorithm effectively minimizes the search area at each step, making it a time-efficient solution for this kind of problem. It ensures the function runs in O(log n) time complexity, where n is the number of elements in the list.

Comments

No comments yet.