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:

  1. shortest_path(start, is_goal, next_states) -> Optional[List[Hashable]]

    • Explore hashable states outward from start using 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 where is_goal(state) is True.
    • Return [start] when start already satisfies is_goal, return None when no goal state is reachable, and support None itself as a valid start state.
  2. river_crossing(items, conflicts) -> Optional[List[Optional[str]]]

    • A boatman and every item in items start on bank 0 and must all finish on bank 1. 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) in conflicts (with both names present in items) 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 None when rowing alone), or None if no valid schedule exists.
  3. water_jugs(a, b, target) -> Optional[List[Tuple[int, int]]]

    • Given integer jug capacities a >= 1 and b >= 1, start from (0, 0). In one operation you may fill either jug to its rim, empty either jug to 0, 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 with jug_a == target or jug_b == target, or None if target cannot be measured.
  4. open_lockers(n) -> List[int]

    • Given n >= 0 initially closed lockers labeled 1 through n, pass k (k = 1..n) toggles every locker whose label is a multiple of k. Return the labels that remain open after all n passes, sorted in ascending order.
  5. trailing_zeros_of_factorial(n) -> int

    • Return how many trailing zeros n! ends with when written in base 10 (n >= 0), without computing n! directly.
  6. find_heavy_coin(weights) -> Tuple[int, int]

    • Given a non-empty sequence weights where n - 1 coins weigh the exact same amount and one coin is strictly heavier (raise ValueError if weights is 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 most ceil(log_3 n) weighings in the worst case.
  7. knights_and_knaves(claims) -> List[Tuple[bool, ...]]

    • Each person i is either a knight (True, always speaks true statements) or a knave (False, always speaks false statements). claims[i] is either None (silent) or a predicate claim(assignment) -> bool.
    • Return all consistent truth assignments ordered identically to itertools.product((True, False), repeat=len(claims)).

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; target is any integer (return None if target < 0, target > max(a, b), or target % gcd(a, b) != 0).
  • open_lockers: 0 <= n <= 10^9 (must run in O(sqrt(n)) time).
  • trailing_zeros_of_factorial: 0 <= n <= 10^18 (must run in O(log n) time).
  • find_heavy_coin: 1 <= len(weights) <= 10^5 (raise ValueError on empty sequence; worst-case weighings must equal ceil(log_3 len(weights))).
  • knights_and_knaves: 0 <= len(claims) <= 12.

Step-by-step walkthrough

  1. 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 (a L and b L -> target L) GCD check + BFS over jug states Divisibility invariant (gcd(a, b)) + boundary state bound
    3. n toggled lockers List perfect squares <= n Divisor pairing (d, m / d)
    4. Trailing zeros of n! Sum n // 5^k Prime factorization (10 = 2 * 5) + Legendre's formula
    5. 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^n truth-table search Soundness 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 k observations can distinguish (3^k), proving impossibility or optimality directly.

  2. 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, ... from start using a first-in, first-out queue (deque) and a parent dictionary 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 d from start is popped and expanded before any state at distance d + 1. Because each state enters parent only the first time it is discovered, its recorded parent sits at distance d - 1. Therefore, the first goal state popped from the queue has minimum possible distance d*, and walking parent pointers back to start reconstructs a valid path of d* 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: Because None is itself a valid hashable Python state, we mark the start state's parent with a private sentinel _ROOT = object() rather than None.

    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 None
    
  3. Puzzle 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 only 2^4 = 16 total tuples (10 of 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_path from (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, cabbage
    

    Hand proof that 7 crossings is minimal: Crossings alternate 0 -> 1 and 1 -> 0 and must finish on bank 1, so any plan has F forward trips and F - 1 return trips (2F - 1 crossings total). Each forward trip moves at most 1 item to bank 1, so moving all 3 items requires F >= 3. Could F = 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 bank 1. - Now bank 1 holds the goat alongside a conflicting item while the third item is still waiting on bank 0! If trip 4 returns empty, the conflict pair on bank 1 is left unattended. Contradiction! At least 1 return trip must carry an item back, forcing F >= 4 forward trips and at least 2(4) - 1 = 7 crossings.

    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 plan
    
  4. Puzzle 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 transfers min(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 (gcd invariant) and O(a + b) state bound: 1. Necessity (GCD invariant): Let g = gcd(a, b). Initially (0, 0) holds multiples of g. Filling sets a jug to a or b (multiples of g), emptying sets it to 0, and pouring adds or subtracts x, y, a - x, or b - y—all sums/differences of multiples of g. By induction, every reachable volume is divisible by g (so 6 L and 9 L jugs with g = 3 can never measure 5 L). 2. Sufficiency: Assume b >= a and 0 <= target <= b is a multiple of g. Repeatedly filling jug A and pouring into jug B (emptying B whenever full) visits every residue (k * a) mod b for k = 0, 1, ..., b/g - 1, which hits every multiple of g up to b by Bezout's identity. 3. Boundary invariant (O(a + b) states, not O(a * b)): Every legal move leaves at least one jug completely empty (0) or completely full (a or b). Thus no interior state (x, y) with 0 < x < a and 0 < y < b is ever visited—BFS explores at most 2(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)
    
  5. Puzzle 3: Toggled lockers and perfect squares

    Start with n closed lockers 1..n. Pass k (k = 1..n) flips every locker whose label is a multiple of k. Which lockers stay open at the end?

    Proof via divisor pairing: Locker m is toggled on pass d if and only if d divides m. Because every locker starts closed, locker m ends open if and only if m has an odd number of positive divisors. Group every divisor d of m with its partner m / 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)  -> OPEN
    

    Every pair (d, m / d) contributes 2 distinct divisors unless d = m / d, i.e., m = d^2. Therefore, m has an odd number of divisors if and only if m is a perfect square ([1, 4, 9, 16, 25] for Example 2's n = 30), listed directly in O(√n) steps instead of O(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 result
    
  6. Puzzle 4: Trailing zeros of n!

    How many zeros appear at the end of n! (such as 60! in Example 2) in base 10 without computing n!?

    Proof via Legendre's formula: Writing n! = 2^a * 5^b * (other primes), each trailing zero corresponds to one factor of 10 = 2 * 5, so the number of trailing zeros is min(a, b). Since every 2nd integer supplies a 2 while only every 5th integer supplies a 5, n // 2^k >= n // 5^k for every k >= 1, meaning a >= b always—factors of 5 are the bottleneck.

    How many 5s divide 1 * 2 * ... * n? - Multiples of 5 (5, 10, 15, ...) contribute their first factor of 5: n // 5 of them. - Multiples of 25 = 5^2 (25, 50, ...) carry a second factor of 5: n // 25 extra. - Multiples of 125 = 5^3 carry a third factor of 5: n // 125 extra, 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 zeros
    
    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
    
  7. Puzzle 5: Finding the heavy coin in fewest weighings

    Given n coins where n - 1 have 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): With m >= 2 remaining candidate coins, set pan_size = ceil(m / 3) = (m + 2) // 3. Notice a critical sanity check: for every integer m >= 2, 2 * ceil(m / 3) <= m (check m = 2 -> 2*1=2, m = 3 -> 2*1=2, m = 4 -> 2*2=4, and for m = 3q + r with q >= 1, 2(q + 1) <= 3q + 1). That guarantees we always have enough coins to put the exact same count pan_size on the left and right pans, leaving m - 2 * pan_size <= pan_size coins off the scale. Trace Example 3 (7 coins with index 4 heavy):

    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), after k weighings at most ceil(n / 3^k) candidates remain, reaching 1 coin as soon as 3^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, or Left == Right). Therefore, any adaptive strategy of k weighings corresponds to a ternary decision tree with at most 3^k leaves. Since each of the n possible heavy-coin indices must lead to a distinct leaf, 3^k >= n, proving k >= 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], weighings
    
  8. Puzzle 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)? Then p[0] == p[1] is true, forcing Speaker 1 to be a knight (True) as well—yet Speaker 1 claims not 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 statement not p[0] gives not False == True, consistent with a knight: [(False, True)].

    General algorithm & proof: Both rules collapse into one equality for every speaker i: - If assignment[i] is True (knight), claim(assignment) must be True. - If assignment[i] is False (knave), claim(assignment) must be False. So speaker i is consistent if and only if bool(claim(assignment)) == assignment[i]. Testing all 2^n boolean 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 solutions
    
  9. Complete 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 and O(V) space, where V is the number of reachable states and E is the number of transitions examined from them, because each reachable state enters parent and the deque once (O(1) pop/append) and its outgoing transitions are scanned once.
  • river_crossing: O(2^n * n * (n + c)) time and O(2^n * n) space for n items and c conflict pairs. There are 2^(n + 1) bank tuples, each tries up to n + 1 passengers, copying a tuple of length n + 1 and checking c conflict pairs (for n = 3 items, 2^4 = 16 states total).
  • water_jugs: O(a + b) time and O(a + b) space. First, math.gcd(a, b) runs in O(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 (a or b), so BFS only ever visits the boundary of the rectangle—at most 2(a + b) states, each generating 6 constant-time moves.
  • open_lockers: O(√n) time and O(1) auxiliary space (excluding the output list of floor(√n) squares), stepping k = 1, 2, ..., floor(√n) directly instead of simulating n/1 + n/2 + ... + n/n = O(n log n) toggles.
  • trailing_zeros_of_factorial: O(log_5 n) time and O(1) space, dividing n by 5, 25, 125, ... at most floor(log_5 n) times using two integers.
  • find_heavy_coin: ceil(log_3 n) weighings, O(n) total arithmetic time, and O(n) space. Each round shrinks the candidate list from m to at most ceil(m / 3), so summing pan weights across all rounds costs n + n/3 + n/9 + ... <= 1.5n additions.
  • knights_and_knaves: O(2^n * n) claim evaluations and O(n) working space (excluding returned solutions) across 2^n truth assignments of n people.

Edge cases

  • start is None in shortest_path: Using a private _ROOT = object() sentinel in parent = {start: _ROOT} ensures None can be the start state without prematurely stopping path reconstruction.
  • Zero items or impossible triangles in river_crossing: With items = [], 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 and river_crossing returns None.
  • Boundary targets in water_jugs: target = 0 succeeds immediately in 0 moves ([(0, 0)]); target > max(a, b) or target % gcd(a, b) != 0 returns None immediately without searching.
  • Small n in open_lockers and trailing_zeros_of_factorial: open_lockers(0) returns []; 0! = 1 has 0 trailing zeros; jumping from 24! (4 zeros) to 25! (6 zeros) adds two zeros at once because 25 = 5^2.
  • Tiny or non-power-of-3 coin counts in find_heavy_coin: 1 coin needs 0 weighings ((0, 0)), 2 or 3 coins need 1 weighing, and 7 coins put ceil(7 / 3) = 3 coins on each pan (1 off-scale) to finish in 2 weighings.
  • Paradoxes and under-determined knights_and_knaves puzzles: "I am a knave" yields [] (False either 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 when state[a] == state[b] AND state[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. Weighing 3 vs. 3 with 7 coins guarantees <= 3 candidates on every branch (2 weighings), whereas splitting unevenly into 4 vs. 4 on 9 coins leaves 4 candidates and forces 3 weighings.
  • Counting only n // 5 for factorial zeros: 60 // 5 = 12 misses the extra factor of 5 hidden inside 25 and 50 (14 zeros total)—a classic Legendre's formula (the rule summing floor(n / p^k) over all powers p^k <= n to count prime p in n!) pitfall. Note also that in fixed-width 32-bit languages, power_of_five *= 5 can overflow INT_MAX, so repeatedly setting n //= 5; count += n is 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_jugs visits O(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 8x8 board in alternating black and white squares: two diagonally opposite corners always share the same color, leaving 32 squares of one color and 30 of the other. Every 1x2 domino covers exactly 1 black square and 1 white square, so 31 dominoes must cover 31 black and 31 white squares (31 != 32 and 31 != 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_path directly with state (m_left, c_left, boat_side), which has at most 4 * 4 * 2 = 32 states! From the current boat_side, try moving (dm, dc) in [(1, 0), (2, 0), (0, 1), (0, 2), (1, 1)] to the opposite bank, keeping only states where 0 <= m <= 3, 0 <= c <= 3, and on both banks either m == 0 or m >= 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^200 enumeration becomes intractable, so you encode each speaker i as a boolean variable x_i and translate each logical statement into conjunctive normal form (CNF) clauses (AND of ORs) tied to x_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 "Person j is a knight/knave", the puzzle reduces to 2-coloring a graph in linear O(V + E) time!

Follow-up questions

Similar questions

More Spokeo interview questions

All 2 Spokeo questions →