Heaps
Whenever the problem says "repeatedly take the largest or smallest and put something back", that is a heap. Several of these are greedy algorithms that need a heap to be fast.
The lesson is Heaps.
k-th smallest across sorted lists
lists is a list of sorted lists. Write kth_smallest(lists, k) that returns the k-th
smallest value across all of them, counting repeats, with k = 1 the smallest. k is at
most the total count.
kth_smallest([[1, 5, 9], [2, 3], [4]], 4) -> 4
kth_smallest([[1, 1], [1]], 3) -> 1
The point is to practise the k-way merge with a heap, stopping after k pops.
def kth_smallest(lists, k):
...
Rooms needed
meetings is a list of (start, end) pairs. A meeting ending at time t frees its room
for one starting at t. Write rooms_needed(meetings) that returns the fewest rooms so
that no two overlapping meetings share one.
rooms_needed([(0, 30), (5, 10), (15, 20)]) -> 2
rooms_needed([(7, 10), (2, 4)]) -> 1
rooms_needed([]) -> 0
The point is to practise a heap of end times: the root is the room that frees up soonest.
def rooms_needed(meetings):
...
No two neighbours alike
Write rearrange(text) that returns a rearrangement of the characters of text in which
no two adjacent characters are the same, or "" if that is impossible. Any valid
arrangement passes.
rearrange("aab") -> "aba"
rearrange("aaab") -> ""
rearrange("aabb") -> "abab" or "baba"
The point is to practise a max-heap by count: always place the most frequent remaining character, but never the one you just placed.
def rearrange(text):
...
Last stone standing
stones is a list of positive weights. Repeatedly take the two heaviest stones and smash
them together: if they are equal both are destroyed, otherwise the lighter is destroyed
and the heavier becomes the difference. Write last_stone(stones) that returns the
weight of the final stone, or 0 if none remain.
last_stone([2, 7, 4, 1, 8, 1]) -> 1
last_stone([3, 3]) -> 0
last_stone([5]) -> 5
The point is to practise simulating "take the two largest" with a max-heap via negation.
def last_stone(stones):
...
k most frequent numbers
Write k_frequent(nums, k) that returns the k values that appear most often, most
frequent first; when two values tie, the smaller comes first. k is at most the number
of distinct values.
k_frequent([1, 1, 1, 2, 2, 3], 2) -> [1, 2]
k_frequent([4, 4, 5, 5, 6], 2) -> [4, 5]
The point is to practise a heap keyed on (-count, value).
def k_frequent(nums, k):
...
Pick the largest k times
piles is a list of positive whole numbers. You make k picks; each pick takes the
largest pile's current value as your score and then halves that pile, rounding up. Write
max_score(piles, k) that returns the total score.
max_score([10, 10, 10, 10, 10], 5) -> 50
max_score([1, 10, 3, 3, 3], 3) -> 18 (10, then 5, then 3)
The point is to practise a heap where popped items go back changed.
def max_score(piles, k):
...
Sort a nearly sorted list
Every item in items is at most k positions away from where it belongs in sorted
order. Write sort_nearly(items, k) that returns the sorted list.
sort_nearly([6, 5, 3, 2, 8, 10, 9], 3) -> [2, 3, 5, 6, 8, 9, 10]
sort_nearly([1, 2, 3], 0) -> [1, 2, 3]
The point is to practise a heap of size k + 1: the smallest of the next k + 1 items
must be the next item of the output. sorted also passes; the heap version is n log k.
def sort_nearly(items, k):
...
k-th largest after each arrival
Write kth_largest_stream(nums, k) that returns a list with, for each position i, the
k-th largest value among nums[0..i], or None when fewer than k values have
arrived.
kth_largest_stream([4, 5, 8, 2], 3) -> [None, None, 4, 4]
kth_largest_stream([3, 1], 1) -> [3, 3]
The point is to practise maintaining a heap of size k across a stream.
def kth_largest_stream(nums, k):
...
Fewest fuel stops
A car starts with fuel units and must travel target units, using one unit per
distance. stations is a list of (position, amount) sorted by position. Write
min_refuels(target, fuel, stations) that returns the fewest stops needed to reach the
target, or -1 if it cannot.
min_refuels(100, 10, [(10, 60), (20, 30), (30, 30), (60, 40)]) -> 2
min_refuels(1, 1, []) -> 0
min_refuels(100, 1, [(10, 100)]) -> -1
The point is to practise a greedy with a heap: pass stations and remember their fuel, and only when stuck, take the biggest amount you passed.
def min_refuels(target, fuel, stations):
...
k-th number with only small factors
A "smooth" number here is a positive whole number whose only prime factors are 2, 3 or 5:
1, 2, 3, 4, 5, 6, 8, 9, 10, 12, .... Write kth_smooth(k) that returns the k-th one.
kth_smooth(1) -> 1
kth_smooth(7) -> 8
kth_smooth(10) -> 12
The point is to practise generating values in order with a heap and a set to avoid repeats: each popped number spawns three candidates.
def kth_smooth(k):
...
Next: Greedy.