Search Insert Position - Problem
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.
Input & Output
Example 1 — Target Found
$
Input:
nums = [1,3,5,6], target = 5
›
Output:
2
💡 Note:
Target 5 exists at index 2, so return 2
Example 2 — Insert in Middle
$
Input:
nums = [1,3,5,6], target = 2
›
Output:
1
💡 Note:
Target 2 should be inserted at index 1 to maintain sorted order: [1,2,3,5,6]
Example 3 — Insert at End
$
Input:
nums = [1,3,5,6], target = 7
›
Output:
4
💡 Note:
Target 7 is larger than all elements, so insert at the end (index 4)
Constraints
- 1 ≤ nums.length ≤ 104
- -104 ≤ nums[i] ≤ 104
- nums contains distinct values sorted in ascending order
- -104 ≤ target ≤ 104
Visualization
Tap to expand
Understanding the Visualization
1
Input
Sorted array [1,3,5,6] and target = 2
2
Process
Find where target should be inserted to maintain order
3
Output
Return index 1 (between 1 and 3)
Key Takeaway
🎯 Key Insight: Binary search leverages the sorted property to find insertion points in O(log n) time
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code