Problem set 3: stacks, binary search and trees
🌍 In real life. These three jobs come from a sticker game, a tile shop and a hill walk. As in Sets 1 and 2, nothing names the technique: read each story for clues, check the size, and only then pick a tool.
The idea in one sentence: clues that point backwards to "the last thing still waiting" suggest a stack, a yes/no question that flips only once as a number grows suggests binary search on the answer, and anything shaped like branching routes from one start suggests recursion on a tree.
Its words:
- stack: last in, first out; its top is "the last thing still waiting"
- binary search on the answer: searching the possible answers, not a list, when a yes/no test flips only once
- subtree result: what a recursive call returns for one child, combined at its parent
This set (Medium): stacks, binary search and trees
- Twin stickers. A child lines up stickers; whenever two identical stickers end up side by side they both peel off, and that can make two new neighbours meet. What is left at the end?
- The biggest square patch. A tile shop has n square tiles. What is the side k of the biggest k × k square patch they can cover, with tiles left over allowed?
- A route that uses all your money. A path splits at junctions down a hill, and every junction charges a toll. Is there a route from the top to a dead end whose tolls add up to exactly the money in your pocket?
How to attack them, step by step:
- write down what each story asks for and the size limits
- look for the clue words: "side by side, again and again", "the biggest that still fits", "from the top to a dead end"
- solve a tiny example by hand
- code it, then test the edge cases (Lesson 61.4)
The stickers first. Stickers 3, 5, 5, 3, 7 go on one by one: the second 5 meets the 5 on top and both go, then the second 3 meets the 3 now on top:
Only 7 is left. For the tiles, the clue "the biggest k with k × k ≤ n" is a yes/no question (does k fit?) that is yes for every k up to the answer and no after it, like a sorted list of answers; with n up to 1,000,000,000 trying every k is far too slow:
Of the two tools the map lights, binary search fits: there is one list of possible answers, not a pair to find.
Why these patterns fit. In the sticker game a sticker can only cancel with the last sticker still standing, and when that one goes, the one before it becomes the last: exactly what a stack's top does. For the tiles, if k fits then every smaller k fits too, so the "fits" answers form one block and binary search can halve the range each time. On the hill, every route to a dead end is a root-to-leaf path in a tree; subtract the junction's toll and ask the same question of each branch.
What it costs, by counting. The stickers are one pass with O(1) work per sticker: O(n) time, O(n) memory for the stack in the worst case (no twins at all). Square root by binary search needs about log₂ n steps: for n = 1,000,000,000 about 30 steps, where counting k up from 0 would take about 31,623. The path sum visits each junction once: O(n) time and O(h) memory for the recursion, where h is the height of the tree.
The three solutions together:
def remove_pairs(s):
kept = [] # a stack of the letters still standing
for ch in s:
if kept and kept[-1] == ch:
kept.pop() # it meets its twin: both disappear
else:
kept.append(ch)
return "".join(kept)
def int_sqrt(n):
lo, hi = 0, n # the answer k is somewhere in 0..n
while lo < hi:
mid = (lo + hi + 1) // 2 # round up, so lo = mid always moves
if mid * mid <= n:
lo = mid # mid fits: the answer is mid or bigger
else:
hi = mid - 1 # too big: the answer is smaller
return lo
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def has_path_sum(root, target):
if root is None:
return False
if root.left is None and root.right is None: # a dead end: does this route add up?
return root.val == target
rest = target - root.val
return has_path_sum(root.left, rest) or has_path_sum(root.right, rest)
print(remove_pairs("abbaca"), int_sqrt(1000000000))
hill = Node(5, Node(4, Node(11, Node(7), Node(2))), Node(8, Node(13), Node(4, None, Node(1))))
print(has_path_sum(hill, 22), has_path_sum(hill, 26), has_path_sum(hill, 25))Mistakes and edge cases.
- removing pairs only once: a pass that deletes "bb" from "abba" leaves "aa", a new pair; the stack handles this, a single pass does not
- an endless binary search: with
mid = (lo + hi) // 2andlo = mid, two neighbouring values loop forever; round up when you movelo mid * midwith floats:n ** 0.5can be off by one for huge n; whole-number binary search is exact- stopping at a node with one child: a dead end has no children at all; a node with only a left child is not the end of a route
- an empty tree: no route at all, so the answer is False, even for target 0
Quiz
"Identical neighbours cancel, and that can make new neighbours meet." Which pattern?
- A stack: compare each item with the last one still standing
- Sorting first
- A sliding window of size 2
What does this print?
def remove_pairs(s): kept = [] # a stack of the letters still standing for ch in s: if kept and kept[-1] == ch: kept.pop() # it meets its twin: both disappear else: kept.append(ch) return "".join(kept) print(remove_pairs("azxxzy"), repr(remove_pairs("abba")))What does this print?
def int_sqrt(n): lo, hi = 0, n # the answer k is somewhere in 0..n while lo < hi: mid = (lo + hi + 1) // 2 # round up, so lo = mid always moves if mid * mid <= n: lo = mid # mid fits: the answer is mid or bigger else: hi = mid - 1 # too big: the answer is smaller return lo print(int_sqrt(0), int_sqrt(8), int_sqrt(16), int_sqrt(99))About how many steps does int_sqrt take for n = 1,000,000,000?
- About 30: O(log n)
- About 31,623: O(√n)
- About 1,000,000,000: O(n)
has_path_sum(Node(1, Node(2)), 1) answers True, though the only dead end is 2 (route total 3). Which line is wrong?
def has_path_sum(root, target): if root is None: return target == 0 rest = target - root.val return has_path_sum(root.left, rest) or has_path_sum(root.right, rest)
Coding tasks
Twin stickers. Write
remove_pairs(s): whenever two equal letters stand side by side, remove both; repeat until no such pair is left, and return what remains (""if nothing does).The biggest square patch. Write
int_sqrt(n): the largest whole numberkwithk * k <= n, forn >= 0. Don't use**,math.sqrtormath.isqrt; it must take O(log n) steps.A route that uses all your money. Write
has_path_sum(root, target):rootis the topNodeof a tree (orNone). ReturnTrueif some route from the root down to a leaf (a node with no children) has values adding up to exactlytarget, elseFalse.