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
Search Insert Position: Find where target=2 belongsInput: nums = [1,3,5,6], target = 21356index 0index 1index 2index 3Insert 2 hereResult array would be: [1, 2, 3, 5, 6]Output: 1
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
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
1.3M Views
High Frequency
~15 min Avg. Time
8.4K 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