Drill

ProblemsPython › patterns

Where a value slots in

mediumpatternsBinary searchArraysPython

A timeseries store keeps an array sorted and needs to know exactly where a new reading would land on insertion.

insert_position(values: list<int>, target: int) → int

Solve it in the editor →

Where you start

def insert_position(values: list[int], target: int) -> int:
    

Worked examples

CallResult
insert_position([1, 3, 5, 6], 5)2
insert_position([1, 3, 5, 6], 2)1
insert_position([1, 3, 5, 6], 7)4
insert_position([1, 3, 5, 6], 0)0

Hint

A lower-bound binary search: hold a window in two indices and ask which half the value must fall in.

Reference solution in Python
def insert_position(values: list[int], target: int) -> int:
    lo, hi = 0, len(values)
    while lo < hi:
        mid = (lo + hi) // 2
        if values[mid] < target:
            lo = mid + 1
        else:
            hi = mid
    return lo

The same problem in another language

More patterns problems in Python