Hard 2: trees, graphs and heaps
Two of these introduce ideas the lessons only mentioned: Dijkstra's algorithm, which is breadth-first search with a heap, and union-find, a dozen lines that answer "are these already connected" fast. The statements explain both.
Serialize and rebuild a tree
Write two functions: serialize(root) that turns a binary tree into a string, and
deserialize(text) that turns that string back into an identical tree. Any format works
as long as the round trip reproduces the tree exactly, including None for an empty tree.
deserialize(serialize(tree)) -> a tree with the same shape and values
Pre-order with a marker for missing children is the usual choice: write val then the
left subtree then the right, and # for None. Rebuilding consumes the tokens in the
same order with recursion. Import TreeNode from checker.
def serialize(root):
...
def deserialize(text):
...
Largest path sum in a tree
A path is any sequence of nodes where each is a parent or child of the next, with no node
repeated; it need not pass through the root or end at a leaf. Write max_path_sum(root)
that returns the largest sum of values along any path in a non-empty binary tree.
max_path_sum([1, 2, 3]) -> 6
max_path_sum([-10, 9, 20, None, None, 15, 7]) -> 42 (15 + 20 + 7)
max_path_sum([-3]) -> -3
At each node, the best path through it is val + best downward left + best downward right, where a negative downward contribution is replaced by zero. The function returns
the best downward path (one side only) to its parent while updating a global best.
def max_path_sum(root):
...
Rebuild a tree from two traversals
Write build(preorder, inorder) that returns the root of the binary tree whose pre-order
and in-order traversals are the two given lists. Values are distinct. Import TreeNode
from checker.
build([3, 9, 20, 15, 7], [9, 3, 15, 20, 7]) -> the tree [3, 9, 20, None, None, 15, 7]
build([], []) -> None
The first pre-order value is the root; its position in the in-order list splits the rest into left and right subtrees. A dictionary from value to in-order index keeps it linear.
def build(preorder, inorder):
...
Word ladder
Write ladder_length(start, end, words) that returns the length (number of words,
including both ends) of the shortest sequence from start to end where each step
changes exactly one letter and every intermediate word is in words. end must be in
words. Return 0 if no such sequence exists.
ladder_length("hit", "cog", ["hot", "dot", "dog", "lot", "log", "cog"]) -> 5 (hit, hot, dot, dog, cog)
ladder_length("hit", "cog", ["hot", "dot", "dog", "lot", "log"]) -> 0
BFS where the neighbours of a word are generated by trying every letter in every position and keeping those in the word set.
def ladder_length(start, end, words):
...
Shortest distances with weights
graph is a dictionary from each node to a list of (neighbour, weight) pairs with
non-negative weights; every node is a key. Write distances(graph, source) that returns a
dictionary from every reachable node to its shortest total distance from source.
graph = {"A": [("B", 4), ("C", 1)], "B": [("D", 1)], "C": [("B", 2), ("D", 5)], "D": []}
distances(graph, "A") -> {"A": 0, "B": 3, "C": 1, "D": 4}
This is Dijkstra's algorithm: breadth-first search with the queue replaced by a heap of
(distance, node), so the closest unsettled node is always processed next.
def distances(graph, source):
...
Cheapest route with at most k stops
flights is a list of (from, to, price) one-way flights among cities numbered 0 to
n - 1. Write cheapest(n, flights, src, dst, k) that returns the cheapest price from
src to dst using at most k intermediate stops, or -1 if impossible.
cheapest(4, [(0, 1, 100), (1, 2, 100), (2, 0, 100), (1, 3, 600), (2, 3, 200)], 0, 3, 1) -> 700
cheapest(3, [(0, 1, 100), (1, 2, 100), (0, 2, 500)], 0, 2, 1) -> 200
cheapest(3, [(0, 1, 100), (1, 2, 100), (0, 2, 500)], 0, 2, 0) -> 500
Dijkstra does not respect the stop limit. Instead relax every edge k + 1 times from a
copy of the previous round's costs (Bellman-Ford, limited to k + 1 rounds).
def cheapest(n, flights, src, dst, k):
...
Cheapest way to connect everything
n towns are numbered 0 to n - 1 and roads lists possible (a, b, cost) links.
Write min_connection_cost(n, roads) that returns the smallest total cost of a set of
roads that connects every town, or -1 if they cannot all be connected.
min_connection_cost(4, [(0, 1, 1), (1, 2, 2), (2, 3, 3), (0, 3, 10), (1, 3, 4)]) -> 6
min_connection_cost(3, [(0, 1, 1)]) -> -1
Kruskal's algorithm: sort roads by cost and take each one that joins two towns not already
connected. "Already connected" is answered by a disjoint-set (union-find): a parent
list where find(x) follows parents to a root, and union(a, b) links one root under the
other. Build it yourself; it is a dozen lines.
def min_connection_cost(n, roads):
...
Largest rectangle in a histogram
heights lists bar heights of width one. Write largest_rectangle(heights) that returns
the area of the largest rectangle that fits entirely inside the bars.
largest_rectangle([2, 1, 5, 6, 2, 3]) -> 10 (5 and 6, height 5, width 2)
largest_rectangle([2, 4]) -> 4
largest_rectangle([]) -> 0
A stack of indices with increasing heights. When a lower bar arrives, every taller bar on the stack has found its right boundary; pop it and compute its rectangle, with the left boundary being the new stack top. A sentinel of height 0 at the end flushes the stack.
def largest_rectangle(heights):
...
Alphabet from a sorted word list
words is a list of words sorted according to an unknown alphabet. Write
alien_order(words) that returns a string of all the letters that appear, in an order
consistent with the list, or "" if the list is contradictory (including a word
appearing after its own longer form, like ["abc", "ab"]). Any consistent order passes.
alien_order(["wrt", "wrf", "er", "ett", "rftt"]) -> "wertf"
alien_order(["z", "x"]) -> "zx"
alien_order(["z", "x", "z"]) -> ""
Each pair of adjacent words gives one constraint from their first differing letter. Then it is a topological sort; a cycle, or a prefix violation, means no answer.
def alien_order(words):
...
Lowest common ancestor in any binary tree
root is a binary tree (not necessarily a search tree) with distinct values that contains
both a and b. Write lca(root, a, b) that returns the value of their lowest common
ancestor.
lca([3, 5, 1, 6, 2, 0, 8, None, None, 7, 4], 5, 1) -> 3
lca([3, 5, 1, 6, 2, 0, 8, None, None, 7, 4], 5, 4) -> 5
lca([3, 5, 1, 6, 2, 0, 8, None, None, 7, 4], 7, 4) -> 2
Without the search-tree rule you cannot steer; recurse into both sides and let each subtree report whether it contains one of the targets. The first node where both sides report, or that is itself a target with the other below, is the answer.
def lca(root, a, b):
...