32/40
Part 8 of 8 · Follow-upsLearn and do
What interviewers ask next
A heap, a sorted list or a balanced tree?
- A heap gives the smallest in O(1), and push and pop in O(log n). Nothing else: no search, no removal from the middle, no order beyond the root.
- A sorted list gives min, max and any rank by index, and binary search. But each insert costs O(n): 23.55 µs for a pop from the front and an insert at 100,000 items, in the race at the start of the lesson.
- A balanced binary search tree, such as a red-black tree, gives O(log n) insert, delete of any item, min and max, and walks in order. Python's standard library has none.
Take the tree when you need to delete arbitrary items, find the next item above a value, or walk a range in order.
The sorting and binary search lesson built the two bisect searches. On a sorted list a, bisect.bisect_left(a, x) returns the first index whose item is at least x, and bisect.bisect_right(a, x) the first index whose item is greater than x.
In the editor, values is a sorted list. Write next_above(values, x): the smallest item greater than x, found with bisect. A heap can't answer that question.