Algorithm Day64 - Search Insert Position
🧩 Problem Description
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.
💬 Examples
Example 1
1 | Input: nums = [1,3,5,6], target = 5 |
Example 2
1 | Input: nums = [1,3,5,6], target = 2 |
Example 3
1 | Input: nums = [1,3,5,6], target = 7 |
💡 Intuition
The array is sorted, so binary search is the best choice.
- Maintain two pointers
left
andright
. - While
left <= right
, check the middle value. - If
nums[mid] == target
, returnmid
. - If
nums[mid] < target
, moveleft = mid + 1
. - Else move
right = mid - 1
.
Finally, left
will be the correct insert position.
🔢 Java Code (Binary Search)
1 | class Solution { |
⏱ Complexity Analysis
- Time: O(log n) due to binary search.
- Space: O(1) since no extra memory is used.
✍️ Summary
- Use binary search instead of linear scan.
- If target not found, the correct insert position is
left
.
Related problems
lc-34
— Find First and Last Position of Element in Sorted Arraylc-704
— Binary Search