Skip to content
LEETFLIX

Search Insert Position

Solve on LeetCode

Easy · binary-search insert index. Real solution for this problem — same player as the hand-authored deep-dives.

01

Problem

Read the prompt, flip through the examples, then steal the idea.

LeetCode 35. Search Insert Position. The copyrighted prompt is on LeetCode. This page is a working binary-search insert index for this problem: editable input, Python, Go, and a step-by-step animation.

Constraints

  • —Player inputs are capped so the animation stays readable.
  • —Match LeetCode's own constraints when you submit there.

Examples

Input

nums =
[1, 3, 5, 6]
target =
5

Output

2

02

Solution

Python and Go. The walkthrough below runs this same code.

Approach 1Optimal▶ Animated

Binary search for the lower bound

Find the first index where nums[i] >= target. That is the found index, or where target would be inserted.

Same halving as binary search. When the range collapses, lo is the insertion point — including n when the target is larger than every value.

Algorithm

  1. While lo < hi, probe mid.
  2. If nums[mid] < target, search the right half; else search the left (keeping mid).
  3. Return lo.
Time
O(log n)
Space
O(1)
Solution.py
class Solution:    def searchInsert(self, nums: list[int], target: int) -> int:        lo, hi = 0, len(nums)        while lo < hi:            mid = (lo + hi) // 2            if nums[mid] < target:                lo = mid + 1            else:                hi = mid        return lo
Watch this run

03

Interactive walkthrough

Playing “Binary search for the lower bound”. Edit the input, hit Run, then scrub.

Approach: Binary search for the lower bound

Loading animation…