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 INPUT Sorted Array: nums 1 idx 0 3 idx 1 5 idx 2 6 idx 3 Target Value: 5 Input Values nums = [1, 3, 5, 6] target = 5 ALGORITHM STEPS 1 Initialize Pointers left=0, right=3 2 Binary Search Loop while left <= right 3 Calculate Mid mid = (0+3)/2 = 1 4 Compare & Adjust nums[1]=3 < 5: left=2 Iteration Trace Iter 1: mid=1, nums[1]=3<5 left=2 Iter 2: mid=2, nums[2]=5==5 FOUND! Return 2 FINAL RESULT Target Found at Index 2 1 3 5 6 Found! Output: 2 Confirmation nums[2] = 5 == target OK - Index 2 is correct! Key Insight: Binary Search achieves O(log n) by eliminating half the search space each iteration. If target not found, 'left' pointer gives the correct insert position to maintain sorted order. This works because left always points to the first element greater than or equal to target. TutorialsPoint - Search Insert Position | Optimal Binary Search Approach
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