Search Insert Position – Solution & Complexity
Solution Walkthrough
Step 1: Understand the Return Value
- If
targetexists in the sorted array, return its index. - If it does not exist, return the position where it could be inserted while keeping the array sorted.
- That insertion position is the first index whose value is greater than or equal to
target.
- If
Step 2: Linear Scan Idea
- A simple solution checks values from left to right.
- Return the first index where
nums[i] >= target. - This is easy but O(n), while the problem asks for O(log n).
Step 3: Use Binary Search
- Because
numsis sorted, binary search can discard half of the remaining positions each step. - Keep a search window
[left, right)whererightis exclusive. - The answer will be the smallest index where the value is at least
target.
- Because
Step 4: Move the Bounds
- If
nums[mid] < target, the insertion point must be to the right ofmid. - Otherwise,
midmight be the answer, so keep it by movingrighttomid. - When the window is empty,
leftis the insertion index.
- If
Step 5: Final Complete Solution
- The same binary search handles found and not-found cases.
- Time complexity is O(log n) because the window halves each iteration.
- Space complexity is O(1).