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
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
โก Linearithmic
Space Complexity
O(1)
Only using a constant number of variables for pointers
โ Linear Space
Constraints
- 1 โค nums.length โค 104
- -104 โค nums[i] โค 104
- nums contains distinct values sorted in ascending order
- -104 โค target โค 104
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code