Taro Logo

Search Insert Position

#185 Most AskedEasy
0 views
Topics:
ArraysBinary Search

Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You must write an algorithm with O(log n) runtime complexity.

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

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the expected behavior if the target is smaller than all elements in the array or larger than all elements?
  2. Can the input array be empty, and if so, what index should be returned?
  3. Are we guaranteed that the input array contains only distinct integers as stated, or could there be edge cases with duplicates?
  4. What data types are we working with for the elements and the target (e.g., standard 32-bit signed integers), and what are the possible ranges for their values?
  5. Should the solution be strictly in-place with no additional memory, or is $O(1)$ auxiliary space complexity acceptable?

Brute Force Solution

Approach

Imagine you are holding a numbered item and need to place it into a sorted lineup of items in its proper spot. The brute force strategy involves examining the lineup step by step from the very beginning to find the exact place where your item belongs.

Here's how the algorithm would work step-by-step:

  1. Stand at the very first position in the lineup.
  2. Compare the item you are holding with the item currently standing at that spot.
  3. If the item in the lineup is larger than or equal to the one you are holding, you have found where your item should go.
  4. If the item in the lineup is smaller, take one step forward to look at the next person.
  5. Repeat this comparison process for every single position in the lineup until you find an item that is larger than yours.
  6. If you reach the very end of the lineup and all existing items are smaller than yours, then your item belongs at the very end of the line.

Code Implementation

def search_insert_position(sorted_numbers, target_value):
    # Scan sequentially to find the first element that is not smaller than our target
    for current_index in range(len(sorted_numbers)):
        if sorted_numbers[current_index] >= target_value:
            return current_index

    # If no larger element exists, the target must be placed at the very end
    return len(sorted_numbers)

Big(O) Analysis

Time Complexity
O(n) – To find the correct insert position, we iterate through the sorted lineup item by item from the very beginning. In the worst-case scenario, where our target is larger than all existing items, we must check every single position, resulting in n comparisons for an input of size n. This linear scan requires a number of operations directly proportional to n, which simplifies to O(n).
Space Complexity
O(1) – The brute force strategy described only utilizes a few primitive variables to iterate through the lineup and compare items step by step. No additional data structures, temporary lists, or recursive calls are created during the process. Therefore, the extra memory required remains constant regardless of the input size N of the sorted lineup.

Optimal Solution

Approach

Instead of scanning through every single item one by one, we can use a clever narrowing strategy similar to looking up a word in a dictionary. By repeatedly checking the middle of our current options and throwing away the half we do not need, we can home in on the correct spot almost instantly.

Here's how the algorithm would work step-by-step:

  1. Imagine you have a long row of sorted items and you want to know where a new item belongs.
  2. Begin by looking directly at the item sitting right in the middle of your current section.
  3. Compare your target item with this middle item to see if your target should go before or after it.
  4. If your target matches or belongs right where the middle item is, you have found your exact spot.
  5. If your target belongs further down the line, completely ignore the middle item and everything to its left, shifting your focus only to the remaining right half.
  6. If your target belongs earlier in the sequence, completely ignore the middle item and everything to its right, shifting your focus only to the remaining left half.
  7. Keep repeating this process of halving your search area until your section shrinks down to a single point.
  8. At that final point, place your target in that exact location, and you will have found the correct insertion spot with maximum efficiency.

Code Implementation

def search_insert(sorted_items, target_item):
    left_bound = 0
    right_bound = len(sorted_items) - 1

    while left_bound <= right_bound:
        middle_index = left_bound + (right_bound - left_bound) // 2
        middle_item = sorted_items[middle_index]

        # Exact match found, so this middle index is the correct position.
        if middle_item == target_item:
            return middle_index

        # Target is larger, so we eliminate the left half and current middle.
        elif middle_item < target_item:
            left_bound = middle_index + 1

        # Target is smaller, so we eliminate the right half and current middle.
        else:
            right_bound = middle_index - 1

    # The search space is exhausted, and left_bound marks the insertion point.
    return left_bound

Big(O) Analysis

Time Complexity
O(log n) – The input size n is the number of elements in the sorted array, and the cost is driven by repeatedly halving the search space. In each step of the binary search, we compare the middle element and discard half of the remaining items. This process of dividing the search boundary in half at each step results in a total number of operations proportional to log base 2 of n, which simplifies to O(log n).
Space Complexity
O(1) – The algorithm relies solely on a few primitive integer variables to track the left, right, and middle boundaries of the search range. These variables occupy a constant amount of memory regardless of the input array size N. No additional data structures, temporary lists, or recursive stack frames are created during the execution. Therefore, the extra memory usage remains entirely fixed and does not scale with N.

Edge Cases

Target is smaller than all elements in the array
How to Handle:
Binary search will narrow down to index zero, returning it as the correct insertion position.
Target is larger than all elements in the array
How to Handle:
Binary search pointers will cross and the left pointer will naturally point to the array length.
Array contains only a single element
How to Handle:
The binary search logic compares the target against this single element and returns either zero or one correctly.
Target matches an element in the middle of the array
How to Handle:
Binary search finds the exact match and immediately returns its current index.
Array contains negative numbers and zeros alongside positive integers
How to Handle:
Standard numerical comparisons in binary search handle negative and positive number ranges without modification.
Maximum sized arrays approaching memory or performance limits
How to Handle:
The logarithmic time complexity ensures the search executes efficiently well within standard time limits.
Integer overflow during mid-index calculation
How to Handle:
Calculating the midpoint using low plus high minus low divided by two prevents potential integer overflow.
0/257 completed