Drill

ProblemsJava › patterns

Where a value slots in

mediumpatternsBinary searchArraysJava

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

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

Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

int insertPosition(List<Integer> values, int target) {
    
}

Worked examples

CallResult
insertPosition(Main.<Integer>ls(1, 3, 5, 6), 5)2
insertPosition(Main.<Integer>ls(1, 3, 5, 6), 2)1
insertPosition(Main.<Integer>ls(1, 3, 5, 6), 7)4
insertPosition(Main.<Integer>ls(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 Java
int insertPosition(List<Integer> values, int target) {
    int lo = 0, hi = values.size();
    while (lo < hi) {
        int mid = (lo + hi) / 2;
        if (values.get(mid) < target) lo = mid + 1;
        else hi = mid;
    }
    return lo;
}

The same problem in another language

More patterns problems in Java