Six Algorithmic Logic and Math Puzzle Solvers
Medium · Coding & Algorithms · Data Scientist · Onsite
Problem Statement
Implement a general breadth-first state-space solver alongside six classic logic and math puzzle functions, each backed by a clean optimality or invariant guarantee:
-
shortest_path(start, is_goal, next_states) -> Optional[List[Hashable]]- Explore hashable states outward from
startusing breadth-first search (next_states(state)returns neighboring states in one transition) and return a shortest list[start, ..., goal]ending at the first discovered state whereis_goal(state)isTrue. - Return
[start]whenstartalready satisfiesis_goal, returnNonewhen no goal state is reachable, and supportNoneitself as a validstartstate.
- Explore hashable states outward from
-
river_crossing(items, conflicts) -> Optional[List[Optional[str]]]- A boatman and every item in
itemsstart on bank0and must all finish on bank1. Only the boatman can row, carrying at most one item from the boatman's current bank per crossing. - Whenever both members of a pair
(u, v)inconflicts(with both names present initems) occupy the same bank while the boatman is on the opposite bank, that state is unsafe and forbidden. - Return a minimum-length list of crossings where each entry is the carried item name (or
Nonewhen rowing alone), orNoneif no valid schedule exists.
- A boatman and every item in
-
water_jugs(a, b, target) -> Optional[List[Tuple[int, int]]]- Given integer jug capacities
a >= 1andb >= 1, start from(0, 0). In one operation you may fill either jug to its rim, empty either jug to0, or pour from one jug into the other until the source is empty or the destination is full. - Return a fewest-operations sequence of
(jug_a, jug_b)states starting at(0, 0)and ending withjug_a == targetorjug_b == target, orNoneiftargetcannot be measured.
- Given integer jug capacities
-
open_lockers(n) -> List[int]- Given
n >= 0initially closed lockers labeled1throughn, passk(k = 1..n) toggles every locker whose label is a multiple ofk. Return the labels that remain open after allnpasses, sorted in ascending order.
- Given
-
trailing_zeros_of_factorial(n) -> int- Return how many trailing zeros
n!ends with when written in base10(n >= 0), without computingn!directly.
- Return how many trailing zeros
-
find_heavy_coin(weights) -> Tuple[int, int]- Given a non-empty sequence
weightswheren - 1coins weigh the exact same amount and one coin is strictly heavier (raiseValueErrorifweightsis empty), locate the heavier coin using a two-pan balance comparison that only compares equal-sized left and right pan totals. - Return
(heavy_index, weighings_used), guaranteeing at mostceil(log_3 n)weighings in the worst case.
- Given a non-empty sequence
-
knights_and_knaves(claims) -> List[Tuple[bool, ...]]- Each person
iis either a knight (True, always speaks true statements) or a knave (False, always speaks false statements).claims[i]is eitherNone(silent) or a predicateclaim(assignment) -> bool. - Return all consistent truth assignments ordered identically to
itertools.product((True, False), repeat=len(claims)).
- Each person
Examples
Example 1
Input:
river_crossing(["wolf", "goat", "cabbage"], [("wolf", "goat"), ("goat", "cabbage")])
water_jugs(4, 7, 6)
Output:
river_crossing -> ["goat", None, "wolf", "goat", "cabbage", None, "goat"]
water_jugs -> [(0, 0), (0, 7), (4, 3), (0, 3), (3, 0), (3, 7), (4, 6)]
Walk-through: Taking "goat" first keeps "wolf" and "cabbage" safely separated; bringing "goat" back on trip 4 prevents "wolf" and "goat" (or "goat" and "cabbage") from being left unattended, finishing in 7 crossings. For 4 L and 7 L jugs, repeatedly filling the 7 L jug and pouring into the 4 L jug leaves 3 L, transfers 3 L into the 4 L jug, refills 7 L, and tops off the remaining 1 L of space in the 4 L jug to leave 6 L in 6 operations.
Example 2
Input:
open_lockers(30)
trailing_zeros_of_factorial(60)
Output:
open_lockers(30) -> [1, 4, 9, 16, 25]
trailing_zeros_of_factorial(60) -> 14
Walk-through: Only perfect squares have an odd number of divisors (1, 4, 9, 16, 25 <= 30), so only those lockers are toggled an odd number of times. In 60!, multiples of 5 contribute 60 // 5 = 12 factors of 5 and multiples of 25 (25, 50) contribute 60 // 25 = 2 extra factors of 5, producing 14 factors of 10 = 2 * 5.
Example 3
Input:
find_heavy_coin([8.0, 8.0, 8.0, 8.0, 9.5, 8.0, 8.0])
knights_and_knaves([lambda p: p[0] == p[1], lambda p: not p[0]])
Output:
find_heavy_coin -> (4, 2)
knights_and_knaves -> [(False, True)]
Walk-through: With 7 coins, weighing [0, 1, 2] against [3, 4, 5] ([6] off-scale) tips right, narrowing suspects to [3, 4, 5]; weighing [3] against [4] ([5] off-scale) tips right again, pinpointing index 4 in 2 == ceil(log_3 7) weighings. In knights_and_knaves, if person 0 were truthful (True), person 1 would also be True, contradicting person 1's claim not p[0]; with p = (False, True), p[0] == p[1] is False (matching liar 0) and not p[0] is True (matching truth-teller 1).
Constraints
river_crossing:0 <= len(items) <= 10; conflict tuples may appear in either order.water_jugs:1 <= a, b <= 2000;targetis any integer (returnNoneiftarget < 0,target > max(a, b), ortarget % gcd(a, b) != 0).open_lockers:0 <= n <= 10^9(must run inO(sqrt(n))time).trailing_zeros_of_factorial:0 <= n <= 10^18(must run inO(log n)time).find_heavy_coin:1 <= len(weights) <= 10^5(raiseValueErroron empty sequence; worst-case weighings must equalceil(log_3 len(weights))).knights_and_knaves:0 <= len(claims) <= 12.
Step-by-step walkthrough
Overview of the six puzzles and two core proof tools
Puzzle Algorithm Proof Technique 1. Boatman, wolf, goat, cabbage BFS over bank states BFS shortest-path optimality + alternating-trip lower bound 2. Water jugs ( aL andbL ->targetL)GCD check + BFS over jug states Divisibility invariant ( gcd(a, b)) + boundary state bound3. ntoggled lockersList perfect squares <= nDivisor pairing (d, m / d)4. Trailing zeros of n!Sum n // 5^kPrime factorization ( 10 = 2 * 5) + Legendre's formula5. Heavy coin on a balance scale Ternary split ( ceil(m / 3)per pan)Information-theoretic lower bound ( 3^k >= n)6. Knights and knaves Exhaustive 2^ntruth-table searchSoundness and completeness over finite assignments Every puzzle here yields to one of two universal tools: - State-space search (BFS): Model every valid configuration as a compact hashable state, list the legal one-step transitions, and explore outward wave by wave. - Invariants and counting bounds: Pin down a property preserved by every transition (divisibility, divisor pairing) or count how many answers
kobservations can distinguish (3^k), proving impossibility or optimality directly.Tool 1: Breadth-first search and why it guarantees fewest moves
Breadth-first search (BFS) explores states in concentric waves of distance
0, 1, 2, ...fromstartusing a first-in, first-out queue (deque) and aparentdictionary that both marks visited states and records how we reached each state first:Wave 0: [start] │ Wave 1: [s1, s2] (1 move from start) │ Wave 2: [s3, s4, goal] (2 moves from start -> first goal popped is guaranteed shortest!)Proof of optimality and completeness: 1. Shortest path: By induction on queue order, every state at minimum distance
dfromstartis popped and expanded before any state at distanced + 1. Because each state entersparentonly the first time it is discovered, its recordedparentsits at distanced - 1. Therefore, the first goal state popped from the queue has minimum possible distanced*, and walkingparentpointers back tostartreconstructs a valid path ofd*moves. 2. Impossibility (None): In a finite state graph, each state is enqueued at most once, so the loop always terminates. If the queue empties without seeing a goal, every reachable state was checked and no solution exists. 3. Sentinel detail: BecauseNoneis itself a valid hashable Python state, we mark the start state's parent with a private sentinel_ROOT = object()rather thanNone.from typing import Callable, Hashable, List, Optional from collections import deque # Unique sentinel marking the start state's parent so `start` itself can safely be `None`. _ROOT = object() def shortest_path(start: Hashable, is_goal: Callable[[Hashable], bool], next_states: Callable[[Hashable], List[Hashable]]) -> Optional[List[Hashable]]: # parent maps each discovered state -> previous state along a shortest path (or _ROOT for start). parent = {start: _ROOT} # FIFO queue explores states in non-decreasing order of distance (0, 1, 2, ... moves). queue = deque([start]) while queue: state = queue.popleft() if is_goal(state): # Walk backward through parent pointers to start, then reverse into forward order. path = [] cur = state while cur is not _ROOT: path.append(cur) cur = parent[cur] path.reverse() return path for nxt in next_states(state): # Record a state only the first time it is seen so its parent is at minimum distance. if nxt not in parent: parent[nxt] = state queue.append(nxt) return NonePuzzle 1: River crossing with conflict pairs
State model: Represent everyone's bank (
0= start bank,1= far bank) as a tuple(boatman, wolf, goat, cabbage). With 4 entities there are only2^4 = 16total tuples (10of them safe). A state is unsafe whenever two conflicting items sit on the same bank while the boatman is on the opposite bank (state[pos_a] == state[pos_b] and state[pos_a] != state[0]).Running
shortest_pathfrom(0, 0, 0, 0)to(1, 1, 1, 1)on Example 1 finds a 7-crossing plan:Crossing Start Bank (0) Far Bank (1) Start B, wolf, goat, cabbage (empty) 1. Row goat ──▶ wolf, cabbage B, goat 2. Row alone ◀── B, wolf, cabbage goat 3. Row wolf ──▶ cabbage B, wolf, goat 4. Row goat ◀── B, goat, cabbage wolf 5. Row cabbage ──▶ goat B, wolf, cabbage 6. Row alone ◀── B, goat wolf, cabbage 7. Row goat ──▶ (empty) B, wolf, goat, cabbageHand proof that 7 crossings is minimal: Crossings alternate
0 -> 1and1 -> 0and must finish on bank1, so any plan hasFforward trips andF - 1return trips (2F - 1crossings total). Each forward trip moves at most 1 item to bank1, so moving all 3 items requiresF >= 3. CouldF = 3(5 crossings, meaning zero items ever ride back on a return trip)? - On trip 1, the boatman must take the goat (taking wolf leaves goat + cabbage; taking cabbage leaves wolf + goat; going alone leaves all three). - Trip 2 returns empty, and trip 3 brings either the wolf or the cabbage to bank1. - Now bank1holds the goat alongside a conflicting item while the third item is still waiting on bank0! If trip 4 returns empty, the conflict pair on bank1is left unattended. Contradiction! At least 1 return trip must carry an item back, forcingF >= 4forward trips and at least2(4) - 1 = 7crossings.from typing import List, Optional, Tuple def river_crossing(items: List[str], conflicts: List[Tuple[str, str]]) -> Optional[List[Optional[str]]]: # State shape: tuple of bank sides (0 = start bank, 1 = far bank) of length len(items) + 1. # Index 0 is the boatman; index i + 1 is items[i], e.g. (boatman, wolf, goat, cabbage) = (0, 0, 1, 0). position = {} for i, name in enumerate(items): position[name] = i + 1 start = tuple([0] * (len(items) + 1)) goal = tuple([1] * (len(items) + 1)) def is_safe(state: Tuple[int, ...]) -> bool: for first, second in conflicts: if first not in position or second not in position: continue pos_a = position[first] pos_b = position[second] # A conflict pair is unsafe only when they share a bank AND the farmer is on the other bank. if state[pos_a] == state[pos_b] and state[pos_a] != state[0]: return False return True def next_states(state: Tuple[int, ...]) -> List[Tuple[int, ...]]: result = [] new_bank = 1 - state[0] # passenger == 0 means the farmer rows alone; passenger > 0 carries items[passenger - 1]. for passenger in range(len(state)): if state[passenger] != state[0]: continue moved_list = list(state) moved_list[0] = new_bank moved_list[passenger] = new_bank moved = tuple(moved_list) if is_safe(moved): result.append(moved) return result def is_goal(state: Tuple[int, ...]) -> bool: return state == goal path = shortest_path(start, is_goal, next_states) if path is None: return None # Convert consecutive bank states into the item carried on each crossing (or None if alone). plan: List[Optional[str]] = [] for before, after in zip(path, path[1:]): carried = None for i, name in enumerate(items): if before[i + 1] != after[i + 1]: carried = name break plan.append(carried) return planPuzzle 2: Measuring 6 liters with 4 L and 7 L jugs
State model:
(x, y)tracks liters in jug A (0 <= x <= a) and jug B (0 <= y <= b). Pouring jug A into jug B transfersmin(x, b - y)liters—stopping the instant A runs dry (x) or B hits its rim (b - y). For Example 1 (a = 4, b = 7, target = 6), BFS finds the unique 6-move plan:(0, 0) ─fill B─▶ (0, 7) ─pour B->A─▶ (4, 3) ─empty A─▶ (0, 3) ─pour B->A─▶ (3, 0) ─fill B─▶ (3, 7) ─pour B->A─▶ (4, 6)Proof of solvability (
gcdinvariant) andO(a + b)state bound: 1. Necessity (GCD invariant): Letg = gcd(a, b). Initially(0, 0)holds multiples ofg. Filling sets a jug toaorb(multiples ofg), emptying sets it to0, and pouring adds or subtractsx,y,a - x, orb - y—all sums/differences of multiples ofg. By induction, every reachable volume is divisible byg(so6 Land9 Ljugs withg = 3can never measure5 L). 2. Sufficiency: Assumeb >= aand0 <= target <= bis a multiple ofg. Repeatedly filling jug A and pouring into jug B (emptying B whenever full) visits every residue(k * a) mod bfork = 0, 1, ..., b/g - 1, which hits every multiple ofgup tobby Bezout's identity. 3. Boundary invariant (O(a + b)states, notO(a * b)): Every legal move leaves at least one jug completely empty (0) or completely full (aorb). Thus no interior state(x, y)with0 < x < aand0 < y < bis ever visited—BFS explores at most2(a + b)boundary states!import math from typing import List, Optional, Tuple def water_jugs(a: int, b: int, target: int) -> Optional[List[Tuple[int, int]]]: # By invariant, neither jug can hold negative water, exceed max(a, b), or hold a non-multiple of gcd(a, b). if target < 0 or target > max(a, b): return None if target % math.gcd(a, b) != 0: return None # State shape: (x, y) = (liters in jug a, liters in jug b). def next_states(state: Tuple[int, int]) -> List[Tuple[int, int]]: x, y = state # Pouring stops as soon as the source jug empties OR the destination jug hits capacity. pour_a_to_b = min(x, b - y) pour_b_to_a = min(y, a - x) return [ (a, y), # fill jug a completely (x, b), # fill jug b completely (0, y), # empty jug a (x, 0), # empty jug b (x - pour_a_to_b, y + pour_a_to_b), # pour jug a into jug b (x + pour_b_to_a, y - pour_b_to_a), # pour jug b into jug a ] def is_goal(state: Tuple[int, int]) -> bool: return state[0] == target or state[1] == target return shortest_path((0, 0), is_goal, next_states)Puzzle 3: Toggled lockers and perfect squares
Start with
nclosed lockers1..n. Passk(k = 1..n) flips every locker whose label is a multiple ofk. Which lockers stay open at the end?Proof via divisor pairing: Locker
mis toggled on passdif and only ifddividesm. Because every locker starts closed, lockermends open if and only ifmhas an odd number of positive divisors. Group every divisordofmwith its partnerm / d:Locker 12 (non-square): (1, 12), (2, 6), (3, 4) -> 6 divisors (even) -> CLOSED Locker 16 (4^2 square): (1, 16), (2, 8), and (4, 4)=4 -> 5 divisors (odd) -> OPENEvery pair
(d, m / d)contributes 2 distinct divisors unlessd = m / d, i.e.,m = d^2. Therefore,mhas an odd number of divisors if and only ifmis a perfect square ([1, 4, 9, 16, 25]for Example 2'sn = 30), listed directly inO(√n)steps instead ofO(n log n)simulated toggles.from typing import List def open_lockers(n: int) -> List[int]: # Locker m is toggled once per divisor d of m. Divisors pair up as (d, m // d), # which are distinct unless m = k * k, so only perfect squares have an odd divisor count. result = [] k = 1 while k * k <= n: result.append(k * k) k += 1 return resultPuzzle 4: Trailing zeros of n!
How many zeros appear at the end of
n!(such as60!in Example 2) in base 10 without computingn!?Proof via Legendre's formula: Writing
n! = 2^a * 5^b * (other primes), each trailing zero corresponds to one factor of10 = 2 * 5, so the number of trailing zeros ismin(a, b). Since every 2nd integer supplies a2while only every 5th integer supplies a5,n // 2^k >= n // 5^kfor everyk >= 1, meaninga >= balways—factors of5are the bottleneck.How many
5s divide1 * 2 * ... * n? - Multiples of5(5, 10, 15, ...) contribute their first factor of5:n // 5of them. - Multiples of25 = 5^2(25, 50, ...) carry a second factor of5:n // 25extra. - Multiples of125 = 5^3carry a third factor of5:n // 125extra, and so on.For n = 60: 60 // 5 + 60 // 25 + 60 // 125 = 12 + 2 + 0 = 14 trailing zeros For n = 250: 250 // 5 + 250 // 25 + 250 // 125 = 50 + 10 + 2 = 62 trailing zerosdef trailing_zeros_of_factorial(n: int) -> int: # Each trailing zero comes from 10 = 2 * 5. Because n! has far more factors of 2 than 5, # Legendre's formula counts factors of 5: floor(n/5) + floor(n/25) + floor(n/125) + ... count = 0 power_of_five = 5 while power_of_five <= n: count += n // power_of_five power_of_five *= 5 return countPuzzle 5: Finding the heavy coin in fewest weighings
Given
ncoins wheren - 1have identical weight and 1 coin is strictly heavier, find the heavy coin on a two-pan balance scale in the fewest worst-case weighings.Why ternary splitting works (
ceil(log_3 n)upper bound): Withm >= 2remaining candidate coins, setpan_size = ceil(m / 3) = (m + 2) // 3. Notice a critical sanity check: for every integerm >= 2,2 * ceil(m / 3) <= m(checkm = 2 -> 2*1=2,m = 3 -> 2*1=2,m = 4 -> 2*2=4, and form = 3q + rwithq >= 1,2(q + 1) <= 3q + 1). That guarantees we always have enough coins to put the exact same countpan_sizeon the left and right pans, leavingm - 2 * pan_size <= pan_sizecoins off the scale. Trace Example 3 (7coins with index4heavy):7 coins: [0, 1, 2] on Left vs. [3, 4, 5] on Right, [6] Off-scale ├── Left heavier ──▶ heavy is in [0, 1, 2] ──▶ weigh [0] vs [1] ([2] off) -> 2 weighings ├── Right heavier ──▶ heavy is in [3, 4, 5] ──▶ weigh [3] vs [4] ([5] off) -> index 4 in 2 weighings! └── Balanced ──▶ heavy is in [6] ──▶ done in 1 weighing!Because
ceil(ceil(m / 3) / 3) = ceil(m / 9), afterkweighings at mostceil(n / 3^k)candidates remain, reaching1coin as soon as3^k >= n, i.e.k = ceil(log_3 n).Information-theoretic proof of optimality (lower bound): Each weighing produces one of at most 3 outcomes (
Left > Right,Right > Left, orLeft == Right). Therefore, any adaptive strategy ofkweighings corresponds to a ternary decision tree with at most3^kleaves. Since each of thenpossible heavy-coin indices must lead to a distinct leaf,3^k >= n, provingk >= ceil(log_3 n)in the worst case.from typing import List, Sequence, Tuple def pan_weight(weights: Sequence[float], coins: List[int]) -> float: """Sum the weights of the coin indices placed on one pan of the balance scale.""" total = 0.0 for coin_idx in coins: total += weights[coin_idx] return total def find_heavy_coin(weights: Sequence[float]) -> Tuple[int, int]: if not weights: raise ValueError("need at least one coin") # candidates holds indices of coins that could still be the single heavy coin. candidates = list(range(len(weights))) weighings = 0 while len(candidates) > 1: # Put ceil(m / 3) coins on each pan; for every m >= 2, 2 * ceil(m / 3) <= m, # so both pans always hold the exact same number of coins and each outcome leaves <= ceil(m / 3). pan_size = (len(candidates) + 2) // 3 left_pan = candidates[:pan_size] right_pan = candidates[pan_size:2 * pan_size] off_scale = candidates[2 * pan_size:] weighings += 1 left_weight = pan_weight(weights, left_pan) right_weight = pan_weight(weights, right_pan) if left_weight > right_weight: candidates = left_pan elif right_weight > left_weight: candidates = right_pan else: candidates = off_scale return candidates[0], weighingsPuzzle 6: Knights and knaves
Knights (
True) always tell the truth; knaves (False) always lie. Trace Example 3: - Speaker 0 says: "Speaker 1 and I are the same type" (p[0] == p[1]). - Speaker 1 says: "Speaker 0 is a knave" (not p[0]).Hand deduction: 1. Could Speaker 0 be a knight (
True)? Thenp[0] == p[1]is true, forcing Speaker 1 to be a knight (True) as well—yet Speaker 1 claimsnot p[0](False), which a knight cannot say! Contradiction, so Speaker 0 is a knave (False). 2. Since Speaker 0 is a knave,p[0] == p[1]must be false, forcing Speaker 1 to be a knight (True). Checking Speaker 1's statementnot p[0]givesnot False == True, consistent with a knight:[(False, True)].General algorithm & proof: Both rules collapse into one equality for every speaker
i: - Ifassignment[i]isTrue(knight),claim(assignment)must beTrue. - Ifassignment[i]isFalse(knave),claim(assignment)must beFalse. So speakeriis consistent if and only ifbool(claim(assignment)) == assignment[i]. Testing all2^nboolean tuples is sound (every returned tuple satisfies every speaker's constraint) and complete (every possible truth assignment is checked).import itertools from typing import Callable, List, Optional, Tuple def knights_and_knaves(claims: List[Optional[Callable[[Tuple[bool, ...]], bool]]]) -> List[Tuple[bool, ...]]: solutions = [] # Assignment shape: tuple of booleans where True = knight (always truthful), False = knave (always lies). for assignment in itertools.product((True, False), repeat=len(claims)): consistent = True for person, claim in enumerate(claims): # Both rules collapse to equality: knight requires True == True, knave requires False == False. if claim is not None and bool(claim(assignment)) != assignment[person]: consistent = False break if consistent: solutions.append(assignment) return solutionsComplete solution
Combining the shared BFS helper and all six puzzle solvers gives the complete module:
from typing import Callable, Hashable, List, Optional, Sequence, Tuple from collections import deque import itertools import math # Unique sentinel marking the start state's parent so `start` itself can safely be `None`. _ROOT = object() def shortest_path(start: Hashable, is_goal: Callable[[Hashable], bool], next_states: Callable[[Hashable], List[Hashable]]) -> Optional[List[Hashable]]: # parent maps each discovered state -> previous state along a shortest path (or _ROOT for start). parent = {start: _ROOT} # FIFO queue explores states in non-decreasing order of distance (0, 1, 2, ... moves). queue = deque([start]) while queue: state = queue.popleft() if is_goal(state): # Walk backward through parent pointers to start, then reverse into forward order. path = [] cur = state while cur is not _ROOT: path.append(cur) cur = parent[cur] path.reverse() return path for nxt in next_states(state): # Record a state only the first time it is seen so its parent is at minimum distance. if nxt not in parent: parent[nxt] = state queue.append(nxt) return None def river_crossing(items: List[str], conflicts: List[Tuple[str, str]]) -> Optional[List[Optional[str]]]: # State shape: tuple of bank sides (0 = start bank, 1 = far bank) of length len(items) + 1. # Index 0 is the boatman; index i + 1 is items[i], e.g. (boatman, wolf, goat, cabbage) = (0, 0, 1, 0). position = {} for i, name in enumerate(items): position[name] = i + 1 start = tuple([0] * (len(items) + 1)) goal = tuple([1] * (len(items) + 1)) def is_safe(state: Tuple[int, ...]) -> bool: for first, second in conflicts: if first not in position or second not in position: continue pos_a = position[first] pos_b = position[second] # A conflict pair is unsafe only when they share a bank AND the farmer is on the other bank. if state[pos_a] == state[pos_b] and state[pos_a] != state[0]: return False return True def next_states(state: Tuple[int, ...]) -> List[Tuple[int, ...]]: result = [] new_bank = 1 - state[0] # passenger == 0 means the farmer rows alone; passenger > 0 carries items[passenger - 1]. for passenger in range(len(state)): if state[passenger] != state[0]: continue moved_list = list(state) moved_list[0] = new_bank moved_list[passenger] = new_bank moved = tuple(moved_list) if is_safe(moved): result.append(moved) return result def is_goal(state: Tuple[int, ...]) -> bool: return state == goal path = shortest_path(start, is_goal, next_states) if path is None: return None # Convert consecutive bank states into the item carried on each crossing (or None if alone). plan: List[Optional[str]] = [] for before, after in zip(path, path[1:]): carried = None for i, name in enumerate(items): if before[i + 1] != after[i + 1]: carried = name break plan.append(carried) return plan def water_jugs(a: int, b: int, target: int) -> Optional[List[Tuple[int, int]]]: # By invariant, neither jug can hold negative water, exceed max(a, b), or hold a non-multiple of gcd(a, b). if target < 0 or target > max(a, b): return None if target % math.gcd(a, b) != 0: return None # State shape: (x, y) = (liters in jug a, liters in jug b). def next_states(state: Tuple[int, int]) -> List[Tuple[int, int]]: x, y = state # Pouring stops as soon as the source jug empties OR the destination jug hits capacity. pour_a_to_b = min(x, b - y) pour_b_to_a = min(y, a - x) return [ (a, y), # fill jug a completely (x, b), # fill jug b completely (0, y), # empty jug a (x, 0), # empty jug b (x - pour_a_to_b, y + pour_a_to_b), # pour jug a into jug b (x + pour_b_to_a, y - pour_b_to_a), # pour jug b into jug a ] def is_goal(state: Tuple[int, int]) -> bool: return state[0] == target or state[1] == target return shortest_path((0, 0), is_goal, next_states) def open_lockers(n: int) -> List[int]: # Locker m is toggled once per divisor d of m. Divisors pair up as (d, m // d), # which are distinct unless m = k * k, so only perfect squares have an odd divisor count. result = [] k = 1 while k * k <= n: result.append(k * k) k += 1 return result def trailing_zeros_of_factorial(n: int) -> int: # Each trailing zero comes from 10 = 2 * 5. Because n! has far more factors of 2 than 5, # Legendre's formula counts factors of 5: floor(n/5) + floor(n/25) + floor(n/125) + ... count = 0 power_of_five = 5 while power_of_five <= n: count += n // power_of_five power_of_five *= 5 return count def pan_weight(weights: Sequence[float], coins: List[int]) -> float: """Sum the weights of the coin indices placed on one pan of the balance scale.""" total = 0.0 for coin_idx in coins: total += weights[coin_idx] return total def find_heavy_coin(weights: Sequence[float]) -> Tuple[int, int]: if not weights: raise ValueError("need at least one coin") # candidates holds indices of coins that could still be the single heavy coin. candidates = list(range(len(weights))) weighings = 0 while len(candidates) > 1: # Put ceil(m / 3) coins on each pan; for every m >= 2, 2 * ceil(m / 3) <= m, # so both pans always hold the exact same number of coins and each outcome leaves <= ceil(m / 3). pan_size = (len(candidates) + 2) // 3 left_pan = candidates[:pan_size] right_pan = candidates[pan_size:2 * pan_size] off_scale = candidates[2 * pan_size:] weighings += 1 left_weight = pan_weight(weights, left_pan) right_weight = pan_weight(weights, right_pan) if left_weight > right_weight: candidates = left_pan elif right_weight > left_weight: candidates = right_pan else: candidates = off_scale return candidates[0], weighings def knights_and_knaves(claims: List[Optional[Callable[[Tuple[bool, ...]], bool]]]) -> List[Tuple[bool, ...]]: solutions = [] # Assignment shape: tuple of booleans where True = knight (always truthful), False = knave (always lies). for assignment in itertools.product((True, False), repeat=len(claims)): consistent = True for person, claim in enumerate(claims): # Both rules collapse to equality: knight requires True == True, knave requires False == False. if claim is not None and bool(claim(assignment)) != assignment[person]: consistent = False break if consistent: solutions.append(assignment) return solutions✅ Submit now — all tests should pass.
Intuition & how it works
Think of logic and math puzzles as falling into two mental buckets: maze exploration and conservation laws. When a puzzle asks for a sequence of moves (like crossing a river or pouring water between jugs), turn every legal arrangement into a dot on a map and every allowed move into an arrow, then run breadth-first search (BFS)—an algorithm that explores outward from the start one ripple (1 move, 2 moves, 3 moves) at a time so the very first time it touches the goal is guaranteed to be the shortest path. When a puzzle asks what ends up open, how many zeros appear, or how few weighings suffice, look for an invariant (a quantity or structural rule that no legal step can violate) or an information-theoretic lower bound (counting how many answers k observations can possibly tell apart).
Trial-and-error guessing fails in interviews for three reasons. Wandering randomly or using depth-first search can loop back to old states or return a 13-move plan when a 7-move plan exists. Simulating huge inputs directly (such as multiplying out 1000! or toggling millions of lockers) wastes work when number theory gives the exact answer in microseconds. Worst of all, saying "I tried a few things and couldn't solve it" never proves impossibility—only an exhausted state search or a violated invariant does.
Walk through Example 3's 7-coin balance puzzle ([8.0, 8.0, 8.0, 8.0, 9.5, 8.0, 8.0], heavy coin at index 4):
1. Compute pan_size = ceil(7 / 3) = 3: place [0, 1, 2] on the left pan, [3, 4, 5] on the right pan, and leave [6] off the scale.
2. Weighing 1: Right (25.5) outweighs Left (24.0), eliminating 4 coins at once and narrowing candidates to [3, 4, 5].
3. Weighing 2: Put [3] on the left pan, [4] on the right pan, and [5] off the scale; Right (9.5) outweighs Left (8.0), uniquely identifying index 4 in 2 weighings—matching ceil(log_3(7)) = 2, which no strategy can beat because 1 weighing only produces 3 outcomes (< 7 coins).
Complexity
shortest_path:O(V + E)time andO(V)space, whereVis the number of reachable states andEis the number of transitions examined from them, because each reachable state entersparentand thedequeonce (O(1)pop/append) and its outgoing transitions are scanned once.river_crossing:O(2^n * n * (n + c))time andO(2^n * n)space fornitems andcconflict pairs. There are2^(n + 1)bank tuples, each tries up ton + 1passengers, copying a tuple of lengthn + 1and checkingcconflict pairs (forn = 3items,2^4 = 16states total).water_jugs:O(a + b)time andO(a + b)space. First,math.gcd(a, b)runs inO(log(min(a, b)))via Euclid's algorithm to reject unsolvable targets immediately. Second, although the full(x, y)grid has(a + 1)(b + 1)pairs, every move leaves at least one jug completely empty (0) or completely full (aorb), so BFS only ever visits the boundary of the rectangle—at most2(a + b)states, each generating 6 constant-time moves.open_lockers:O(√n)time andO(1)auxiliary space (excluding the output list offloor(√n)squares), steppingk = 1, 2, ..., floor(√n)directly instead of simulatingn/1 + n/2 + ... + n/n = O(n log n)toggles.trailing_zeros_of_factorial:O(log_5 n)time andO(1)space, dividingnby5, 25, 125, ...at mostfloor(log_5 n)times using two integers.find_heavy_coin:ceil(log_3 n)weighings,O(n)total arithmetic time, andO(n)space. Each round shrinks the candidate list frommto at mostceil(m / 3), so summing pan weights across all rounds costsn + n/3 + n/9 + ... <= 1.5nadditions.knights_and_knaves:O(2^n * n)claim evaluations andO(n)working space (excluding returned solutions) across2^ntruth assignments ofnpeople.
Edge cases
start is Noneinshortest_path: Using a private_ROOT = object()sentinel inparent = {start: _ROOT}ensuresNonecan be the start state without prematurely stopping path reconstruction.- Zero items or impossible triangles in
river_crossing: Withitems = [], the boatman crosses once alone ([None]); if three items form a conflict triangle(wolf, goat), (goat, cabbage), (wolf, cabbage), every first crossing leaves a conflicting pair behind andriver_crossingreturnsNone. - Boundary targets in
water_jugs:target = 0succeeds immediately in 0 moves ([(0, 0)]);target > max(a, b)ortarget % gcd(a, b) != 0returnsNoneimmediately without searching. - Small
ninopen_lockersandtrailing_zeros_of_factorial:open_lockers(0)returns[];0! = 1has0trailing zeros; jumping from24!(4zeros) to25!(6zeros) adds two zeros at once because25 = 5^2. - Tiny or non-power-of-3 coin counts in
find_heavy_coin:1coin needs0weighings ((0, 0)),2or3coins need1weighing, and7coins putceil(7 / 3) = 3coins on each pan (1off-scale) to finish in2weighings. - Paradoxes and under-determined
knights_and_knavespuzzles: "I am a knave" yields[](Falseeither way); "I am a knight" yields both[(True,), (False,)]; silent people (None) impose no constraint.
Common mistakes
- Using depth-first search (DFS) when asked for the minimum number of moves: DFS dives down the first valid branch it sees and can return a needlessly long sequence; BFS (or iterative-deepening DFS) is required to guarantee shortest paths on unweighted graphs.
- Forgetting the boatman's location in
is_safe: Conflicting items CAN stand on the same bank safely while the boatman is on that bank; danger occurs only whenstate[a] == state[b]ANDstate[a] != state[0]. - Dividing coins in half instead of thirds on a balance scale: A two-pan balance gives 3 pieces of information (
<,>,==), not 2. Weighing3vs.3with7coins guarantees<= 3candidates on every branch (2weighings), whereas splitting unevenly into4vs.4on9coins leaves4candidates and forces3weighings. - Counting only
n // 5for factorial zeros:60 // 5 = 12misses the extra factor of5hidden inside25and50(14zeros total)—a classic Legendre's formula (the rule summingfloor(n / p^k)over all powersp^k <= nto count primepinn!) pitfall. Note also that in fixed-width 32-bit languages,power_of_five *= 5can overflowINT_MAX, so repeatedly settingn //= 5; count += nis safer there. - Treating a knave as "sometimes lies": A knave always lies (
claim(assignment) == False), which pins down assignments just as tightly as a knight's truth. - Claiming
water_jugsvisitsO(a * b)states: Because partial pours that stop mid-jug are illegal without markers on the jug walls, interior(x, y)pairs are unreachable from(0, 0).
Follow-up questions
- Can 31 dominoes tile an 8x8 board after two diagonally opposite corner squares are removed, and how do you prove it without search? No—and a parity invariant proves it in two sentences without exploring any placements. Color the
8x8board in alternating black and white squares: two diagonally opposite corners always share the same color, leaving32squares of one color and30of the other. Every1x2domino covers exactly 1 black square and 1 white square, so 31 dominoes must cover31black and31white squares (31 != 32and31 != 30), making a tiling impossible. - How would you adapt your state-space search to solve the three-missionaries and three-cannibals two-seat boat puzzle? Reuse
shortest_pathdirectly with state(m_left, c_left, boat_side), which has at most4 * 4 * 2 = 32states! From the currentboat_side, try moving(dm, dc)in[(1, 0), (2, 0), (0, 1), (0, 2), (1, 1)]to the opposite bank, keeping only states where0 <= m <= 3,0 <= c <= 3, and on both banks eitherm == 0orm >= c(so missionaries are never outnumbered); BFS returns the shortest 11-crossing schedule. - How does knights-and-knaves deduction scale when there are 200 speakers instead of 5? Exhaustive
2^200enumeration becomes intractable, so you encode each speakerias a boolean variablex_iand translate each logical statement into conjunctive normal form (CNF) clauses (ANDofORs) tied tox_i <-> statement_i, then hand the formula to a SAT solver (an engine that determines whether boolean variables can satisfy a logical formula using unit propagation and conflict-driven clause learning). Note that when every statement is simply "Personjis a knight/knave", the puzzle reduces to 2-coloring a graph in linearO(V + E)time!
Follow-up questions
- Can 31 dominoes tile an 8x8 board after two diagonally opposite corner squares are removed, and how do you prove it without search?
- How would you adapt your state-space search to solve the three-missionaries and three-cannibals two-seat boat puzzle?
- How does knights-and-knaves deduction scale when there are 200 speakers instead of 5?
Similar questions
- Core Statistical Inference and Distribution Fundamentals
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One