Skip to Content
Read

Sorting and searching

List, sorted, sort(by:), first_ge and friends, binary search on the answer.

Most Div 2 B and C problems sort something, then search it. This chapter covers the growable List, sorting with a key, the four lookups on sorted data, and binary search over an answer.

Lists

An array over a domain has a fixed size. A List<T> grows:

Output
Press Run (Ctrl+Enter).

[expr for x in seq if cond] builds a list in one line.

Sorting

xs.sorted() returns a sorted copy; xs.sort() sorts a var in place. To sort by something else, give a key with by:. A tuple key compares its parts in order, and a negated number sorts descending:

Output
Press Run (Ctrl+Enter).

by: takes a key, never a comparator, so there is no a < b function that is subtly not a strict order.

Searching sorted data

On sorted data, four methods find a position by binary search in O(log n). Each is named for what it returns, and returns None when there is no such element:

CallReturns the index of
b.first_ge(x)the first element ≥ x
b.first_gt(x)the first element > x
b.last_le(x)the last element ≤ x
b.last_lt(x)the last element < x
Output
Press Run (Ctrl+Enter).

This prints, for each x, how many values are smaller than x and how many equal it. ?? n covers "every value is smaller".

Binary search on the answer

When "can it be done with k?" is false and then true as k grows, the smallest good k is (lo..=hi).first_true(ok); last_true finds the largest k for which a condition holds. Both return ?Int:

Output
Press Run (Ctrl+Enter).

Splitting 7 2 5 10 8 into at most 3 consecutive pieces, the largest piece sum can be kept down to 14 (7 2 5 | 10 | 8). The search range starts at a.max()!, where every element fits in a piece of its own, so pieces never meets an element above cap.

Problem: At most

For each of q queries x, print how many of n given integers are at most x. For 5 1 4 1 9 and x = 4 the answer is 3.

3 tests · Ctrl+Enter
Hints

Sort once; the answer is b.first_gt(x) ?? n.

More like this: Closest values. Next: Greedy and two pointers.

Lints for these patterns

cpl lint, the editor and the playground flag the hand-written versions of what this chapter teaches:

On this page