Understanding Search Insert Position
Return the first index whose value is at least target, or nums.length if all values are smaller.
How it works
A half-open search finds the first valid insertion position even among duplicates.
Search the interval [left, right). Discard mid and earlier values when nums[mid] is too small. Otherwise keep mid as a possible answer by moving right to mid.
Try an example
Input: nums = [1, 3, 5, 6], target = 2
Output: 1
A half-open search finds the first valid insertion position even among duplicates.
Constraints
- 0–64 integers sorted in nondecreasing order; duplicates are allowed.
- Target is an integer between -1,000,000 and 1,000,000.
Use the simulator
Change the input, then choose Visualize input. Use Next and Previous to inspect each decision, or Play to advance automatically. Compare approaches and their complexity. Choose Try yourself to write JavaScript, select My code and Visualize code to inspect its execution, or Run Tests to check results.
Execution happens in your browser. Drafts are saved locally; avoid entering secrets or sensitive information.