Search Insert Position
Find the first position at which the target can be inserted before any equal values while preserving order.
Find the first position at which the target can be inserted before any equal values while preserving order.
Input and constraints
- Values must be in nondecreasing order.
- Use at most 32 integers. Each numeric input is between -1000 and 1000.
Code inspector
def solve(values, target): left = 0 right = len(values) while (left < right): mid = (left + ((right - left) // 2)) if (values[mid] < target): left = (mid + 1) else: right = mid return leftVisualizer
Step 1 of 4Inspect the current state
Check which side of the boundary contains the midpoint.
Variable watch
Step explanation
Check which side of the boundary contains the midpoint.
Worked explanation
Locate the dividing line between two adjacent seating sections; the first seat of one ends the other.
Guided solution
Maintain a half-open range. Every item removed on the left is on the known lower side of the boundary.
O(log n) time · O(1) auxiliary space
Examples
Worked example · {"values":[1,3,3,3,7],"target":3} ⇒ 1
Edge case 1 · {"values":[],"target":5} ⇒ 0
Edge case 2 · {"values":[1,2],"target":4} ⇒ 2
Progressive hints
Hint 1
Locate the dividing line between two adjacent seating sections; the first seat of one ends the other.Hint 2
Maintain a half-open range. Every item removed on the left is on the known lower side of the boundary.Hint 3
Step through the worked example and inspect the highlighted variables before each update.Common mistake
Stopping at the first equality can land in the middle of duplicate values.
Interview follow-up
Which inequality moves the boundary beyond every duplicate?