#35

Search Insert Position

Easy
ArrayBinary SearchBinary SearchArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution (Binary Search)
Time
O(n)
O(log n)
Space
O(1)
O(1)
💡

Intuition

Time O(log n)Space O(1)

Since the array is sorted, we can use binary search to efficiently find the target or the insertion point. This approach reduces the search space by half with each iteration, leading to a logarithmic time complexity.

⚙️

Algorithm

6 steps
  1. 1Step 1: Initialize two pointers, left at 0 and right at the length of the array.
  2. 2Step 2: While left is less than right, calculate the mid index.
  3. 3Step 3: If the mid element equals the target, return mid.
  4. 4Step 4: If the mid element is less than the target, move the left pointer to mid + 1.
  5. 5Step 5: If the mid element is greater than the target, move the right pointer to mid.
  6. 6Step 6: After the loop, left will be the insertion point.
solution.py18 lines
1# Full working Python code with comments
2
3def search_insert(nums, target):
4    left, right = 0, len(nums)
5    while left < right:
6        mid = (left + right) // 2
7        if nums[mid] == target:
8            return mid  # Target found
9        elif nums[mid] < target:
10            left = mid + 1  # Move right
11        else:
12            right = mid  # Move left
13    return left  # Insertion point
14
15# Example usage
16print(search_insert([1, 3, 5, 6], 5))  # Output: 2
17print(search_insert([1, 3, 5, 6], 2))  # Output: 1
18print(search_insert([1, 3, 5, 6], 7))  # Output: 4

Complexity note: This complexity is achieved because we are halving the search space with each iteration, making it much faster than the brute-force approach.

  • 1The sorted nature of the array allows for the use of binary search, which is a powerful technique for searching in sorted data.
  • 2Understanding the difference between searching for an element and finding an insertion point is crucial in array problems.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.