Search Insert Position - Problem

Given a sorted array of distinct integers and a target value, your task is to find the exact position where the target belongs in the array.

If the target is already present, return its index. If it's not found, return the index where it would need to be inserted to keep the array sorted in ascending order.

The challenge: You must solve this with O(log n) time complexity, making it perfect for practicing binary search techniques!

Example: In array [1, 3, 5, 6] with target 5, return index 2. With target 2, return index 1 (where 2 should be inserted).

Input & Output

example_1.py โ€” Target Found
$ Input: nums = [1,3,5,6], target = 5
โ€บ Output: 2
๐Ÿ’ก Note: Target 5 exists in the array at index 2, so we return 2.
example_2.py โ€” Insert Position
$ Input: nums = [1,3,5,6], target = 2
โ€บ Output: 1
๐Ÿ’ก Note: Target 2 doesn't exist, but should be inserted at index 1 to maintain sorted order: [1,2,3,5,6].
example_3.py โ€” Insert at End
$ Input: nums = [1,3,5,6], target = 7
โ€บ Output: 4
๐Ÿ’ก Note: Target 7 is larger than all elements, so it should be inserted at the end (index 4).

Visualization

Tap to expand
13560123Binary Search: O(log n) comparisonsTARGET5Search Steps:1. left=0, right=3, mid=1 nums[1]=3 < 5, go right2. left=2, right=3, mid=2 nums[2]=5 = 5, found!Result: index 2
Understanding the Visualization
1
Start in the Middle
Like opening a phone book to the middle page, we check the middle element first
2
Compare and Eliminate
If the middle element is too small, we know our target must be in the right half
3
Repeat the Process
We continue halving the search space until we find our target or determine where it belongs
4
Find the Position
When pointers cross, the left pointer indicates exactly where the target should be inserted
Key Takeaway
๐ŸŽฏ Key Insight: Binary search eliminates half the possibilities with each comparison, making it exponentially faster than linear search for sorted data

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(log n)

Each comparison eliminates half of the remaining elements

n
2n
โšก Linearithmic
Space Complexity
O(1)

Only using a constant number of variables for pointers

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 104
  • -104 โ‰ค nums[i] โ‰ค 104
  • nums contains distinct values sorted in ascending order
  • -104 โ‰ค target โ‰ค 104
Asked in
Amazon 45 Google 38 Microsoft 32 Meta 28
89.6K Views
Very High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen