Equalizing Nine Stones Across a 3x3 Grid

Medium · Coding & Algorithms · Software Engineer · Online Assessment

Problem Statement

A 3 x 3 board grid holds 9 stones distributed across its nine squares, where grid[r][c] gives the initial stone count at row r and column c (0 <= r, c < 3). Individual squares may start empty (0) or hold stacks of multiple stones.

During each step, you may pick up one stone from any non-empty square and place it onto an edge-adjacent square (one row up/down or one column left/right). Intermediate stacks of arbitrary height are allowed.

Compute the smallest number of single-stone steps required so that all nine squares end up holding 1 stone apiece.

def minimum_moves(grid: list[list[int]]) -> int:
    pass

Examples

Example 1

Input: grid = [
  [0, 1, 1],
  [1, 1, 1],
  [1, 1, 2]
]
Output: 4

Only square (0, 0) is empty and only square (2, 2) holds an extra stone. Walking that extra stone two rows up and two columns left takes |2 - 0| + |2 - 0| = 4 steps.

Example 2

Input: grid = [
  [4, 0, 0],
  [1, 1, 0],
  [1, 2, 0]
]
Output: 7

Four squares start empty: (0, 1), (0, 2), (1, 2), and (2, 2). Square (0, 0) has 3 extra stones and square (2, 1) has 1 extra stone: - Send the extra stone at (2, 1) right to (2, 2) (1 step). - Send the three extra stones at (0, 0) to (0, 1) (1 step), (0, 2) (2 steps), and (1, 2) (3 steps). Total steps: 1 + 1 + 2 + 3 = 7.

Example 3

Input: grid = [
  [0, 0, 2],
  [1, 3, 0],
  [0, 2, 1]
]
Output: 5

Empty squares sit at (0, 0), (0, 1), (1, 2), and (2, 0), while extra stones sit at (0, 2) (+1), (1, 1) (+2), and (2, 1) (+1). Sending (1, 1) -> (0, 0) (2 steps), (1, 1) -> (0, 1) (1 step), (0, 2) -> (1, 2) (1 step), and (2, 1) -> (2, 0) (1 step) achieves the optimal total of 5 steps.

Constraints

  • len(grid) == 3 and len(grid[r]) == 3 for 0 <= r < 3
  • 0 <= grid[r][c] <= 9 for all 0 <= r, c < 3
  • The sum of all nine entries in grid equals 9

Step-by-step walkthrough

  1. Understand the goal: surplus stones vs. empty cells

    We receive a 3 x 3 board holding 9 stones in total. Each move transfers a single stone up, down, left, or right into a neighboring cell, and we want the fewest moves so every cell finishes with 1 stone.

    Every cell plays one of three roles:

    • Balanced (grid[r][c] == 1): already holds the 1 stone it needs.
    • Empty (grid[r][c] == 0): needs 1 stone delivered to it.
    • Surplus (grid[r][c] > 1): retains 1 stone for itself and has grid[r][c] - 1 extra stones that must depart.
    Example 2 grid:              Roles of each cell:
      col 0  col 1  col 2
    [   4,     0,     0  ]  row 0    [ +3 extra,  empty,    empty ]
    [   1,     1,     0  ]  row 1    [  keep 1,   keep 1,   empty ]
    [   1,     2,     0  ]  row 2    [  keep 1,  +1 extra,  empty ]
    

    Because 9 cells hold 9 stones altogether, the total count of extra stones across surplus cells always matches the number of empty cells.

  2. Why moves equal Manhattan distances

    Stones step one square at a time, yet two geometric facts let us skip individual hops and work directly with distances:

    1. No stone ever blocks another. Every cell can hold arbitrarily many passing stones at once, so a stone traveling from (r1, c1) to (r2, c2) can always follow a shortest grid path of length |r1 - r2| + |c1 - c2|, known as the Manhattan distance.
    2. Only surplus stones ever need to move. Suppose stone A walks into cell M, while stone B (which started at M) walks onward to empty cell E. Leaving B parked in M and sending A straight to E obeys the triangle inequality (a direct path between two points is never longer than detouring via a third point), guaranteeing dist(A, E) <= dist(A, M) + dist(M, E):
    Relay plan:   A -----> M (B leaves M) -----> E   cost = dist(A, M) + dist(M, E)
    Direct plan:  A ----------------------------> E   cost = dist(A, E)  (never larger!)
                           B stays home in M
    

    Repeating that exchange converts any valid step sequence into an equally short or shorter plan where every non-empty cell keeps one of its initial stones and each surplus stone walks straight to one empty cell. Our task reduces to matching each empty cell with one surplus stone to minimize total Manhattan distance.

  3. Why greedy fails and why backtracking is fast

    A tempting shortcut is to assign each empty cell whichever surplus stone sits closest. That greedy rule breaks whenever two empty cells compete for the same nearby stone:

    Grid:
      col 0  col 1  col 2
    [   0,     2,     0  ]  row 0    Empty cells: (0, 0) and (0, 2)
    [   1,     1,     1  ]  row 1    Surplus (+1 each): (0, 1) and (2, 0)
    [   2,     1,     1  ]  row 2
    
    Greedy (fill (0, 0) from nearest):
      (0, 1) -> (0, 0) costs 1, forcing (2, 0) -> (0, 2) at cost 4   => total = 5 (suboptimal!)
    
    Optimal pairing:
      (2, 0) -> (0, 0) costs 2, and (0, 1) -> (0, 2) costs 1         => total = 3
    

    Instead, we apply backtracking — systematically testing every available surplus cell for the current empty cell, recursing on the remaining empty cells, and restoring the count afterward so sibling branches start from a clean slate.

    Why is exhaustive backtracking fast here? At most 8 cells can be empty (8! = 40,320 permutations at worst). Even better, extra stones stacked in the same cell are indistinguishable, so branching by source cell rather than individual stone visits at most 90 complete assignments (271 recursive calls total) across all 24,310 valid 3 x 3 boards.

  4. Copy the grid and collect empty cells

    Because backtracking temporarily decrements stone counts during the search, we copy grid into counts first so the caller's matrix is never mutated, then collect every (r, c) coordinate where counts[r][c] == 0 into empty_cells.

    def minimum_moves(grid: list[list[int]]) -> int:
        # Phase 1: Copy the 3x3 grid so backtracking never mutates the caller's input.
        # counts[r][c] stores how many stones currently sit in row r, column c.
        counts = [row[:] for row in grid]
    
        # empty_cells: list of (row, col) coordinates that start with 0 stones and need 1.
        empty_cells: List[Tuple[int, int]] = []
        for r in range(3):
            for c in range(3):
                if counts[r][c] == 0:
                    empty_cells.append((r, c))
    
  5. Backtrack over surplus sources for each empty cell

    Next, fill_empty_cells(empty_idx) computes the minimum moves required to satisfy empty_cells[empty_idx:] using the surplus stones still remaining in counts:

    • Base case: when empty_idx == len(empty_cells), all empty cells are filled and 0 moves remain.
    • Recursive step: take target_row, target_col = empty_cells[empty_idx] and try every (src_row, src_col) with counts[src_row][src_col] > 1. Requiring strict > 1 guarantees a cell never donates its final stone.
    • Decrement counts[src_row][src_col], recurse on empty_idx + 1, and restore counts[src_row][src_col] immediately upon return.
        # Phase 2: Try every way to assign one surplus stone to each empty cell.
        def fill_empty_cells(empty_idx: int) -> int:
            # Base case: all empty cells have been paired with a surplus stone.
            if empty_idx == len(empty_cells):
                return 0
    
            target_row, target_col = empty_cells[empty_idx]
            min_total_moves = float("inf")
    
            for src_row in range(3):
                for src_col in range(3):
                    # Strictly > 1 because every occupied cell must keep 1 stone for itself;
                    # only stones beyond the first are surplus that can move away.
                    if counts[src_row][src_col] > 1:
                        # Manhattan distance is exact because cells have unlimited capacity,
                        # so stones never block one another on a shortest grid path.
                        move_distance = abs(src_row - target_row) + abs(src_col - target_col)
    
                        # Choose: spend one surplus stone from (src_row, src_col).
                        counts[src_row][src_col] -= 1
                        remaining_moves = fill_empty_cells(empty_idx + 1)
                        # Undo (backtrack): put the stone back so the next branch sees the same state.
                        counts[src_row][src_col] += 1
    
                        candidate_moves = move_distance + remaining_moves
                        if candidate_moves < min_total_moves:
                            min_total_moves = candidate_moves
    
            return int(min_total_moves)
    
  6. Trace Example 2 step by step

    Let's trace grid = [[4, 0, 0], [1, 1, 0], [1, 2, 0]]:

    empty_cells = [(0, 1), (0, 2), (1, 2), (2, 2)]
    Surplus sources at start: (0, 0) has count 4 (+3 extra), (2, 1) has count 2 (+1 extra)
    
    Winning branch:
      empty_idx = 0, target (0, 1) <- pick (0, 0): dist |0-0| + |0-1| = 1, counts[0][0] becomes 3
      empty_idx = 1, target (0, 2) <- pick (0, 0): dist |0-0| + |0-2| = 2, counts[0][0] becomes 2
      empty_idx = 2, target (1, 2) <- pick (0, 0): dist |0-1| + |0-2| = 3, counts[0][0] becomes 1 (no more extra!)
      empty_idx = 3, target (2, 2) <- pick (2, 1): dist |2-2| + |1-2| = 1, counts[2][1] becomes 1
      empty_idx = 4 (base case)    -> returns 0
      Total = 1 + 2 + 3 + 1 = 7
    
    Suboptimal branch (for comparison):
      If (2, 1) is spent early on (1, 2) (dist 2), then (2, 2) must pull from (0, 0) (dist 4),
      giving 1 + 2 + 2 + 4 = 9 > 7 (discarded).
    

    Every recursive branch restores counts cleanly on the way back up, and fill_empty_cells(0) returns 7.

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def minimum_moves(grid: list[list[int]]) -> int:
        # Phase 1: Copy the 3x3 grid so backtracking never mutates the caller's input.
        # counts[r][c] stores how many stones currently sit in row r, column c.
        counts = [row[:] for row in grid]
    
        # empty_cells: list of (row, col) coordinates that start with 0 stones and need 1.
        empty_cells: List[Tuple[int, int]] = []
        for r in range(3):
            for c in range(3):
                if counts[r][c] == 0:
                    empty_cells.append((r, c))
    
        # Phase 2: Try every way to assign one surplus stone to each empty cell.
        def fill_empty_cells(empty_idx: int) -> int:
            # Base case: all empty cells have been paired with a surplus stone.
            if empty_idx == len(empty_cells):
                return 0
    
            target_row, target_col = empty_cells[empty_idx]
            min_total_moves = float("inf")
    
            for src_row in range(3):
                for src_col in range(3):
                    # Strictly > 1 because every occupied cell must keep 1 stone for itself;
                    # only stones beyond the first are surplus that can move away.
                    if counts[src_row][src_col] > 1:
                        # Manhattan distance is exact because cells have unlimited capacity,
                        # so stones never block one another on a shortest grid path.
                        move_distance = abs(src_row - target_row) + abs(src_col - target_col)
    
                        # Choose: spend one surplus stone from (src_row, src_col).
                        counts[src_row][src_col] -= 1
                        remaining_moves = fill_empty_cells(empty_idx + 1)
                        # Undo (backtrack): put the stone back so the next branch sees the same state.
                        counts[src_row][src_col] += 1
    
                        candidate_moves = move_distance + remaining_moves
                        if candidate_moves < min_total_moves:
                            min_total_moves = candidate_moves
    
            return int(min_total_moves)
    
        return fill_empty_cells(0)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture 9 chairs arranged in a 3 x 3 room with 9 people sitting in them — some chairs have two, three, or four people squeezed together while other chairs sit empty. Nobody who already has their own chair needs to stand up; each extra person simply walks down the rows and columns to claim one empty chair, and we want the smallest combined walking distance across everyone who moves.

Simulating single-square nudges across full board states is needlessly intricate and obscures which extra stone ends up in which empty square. Conversely, a naive greedy rule — letting each empty square grab whichever extra stone sits closest — fails when an early square claims a nearby stone and forces a later square to pull a stone from across the board. Because squares can hold any number of passing stones at once, sending a stone from (r1, c1) to (r2, c2) always costs its Manhattan distance (|r1 - r2| + |c1 - c2|, the sum of vertical and horizontal grid steps), and we find the globally optimal assignment via backtracking (testing every eligible source square for each empty square one by one, and undoing each tentative choice before trying the next).

Let's walk through a compact example: grid = [[0, 2, 0], [1, 1, 1], [2, 1, 1]]. 1. Scanning the board finds two empty squares, (0, 0) and (0, 2), and two squares with extra stones (count > 1), (0, 1) and (2, 0). 2. For the first empty square (0, 0), branch A assigns the extra stone at (0, 1) (distance 1), leaving (2, 0) for (0, 2) (distance 4), totaling 1 + 4 = 5 steps. 3. Backtracking restores (0, 1)'s count and explores branch B: (0, 0) takes the extra stone from (2, 0) (distance 2), leaving (0, 1) for (0, 2) (distance 1), totaling 2 + 1 = 3 steps. 4. Both branches complete, and the function returns min(5, 3) = 3.

Complexity

  • Time: O(1) because the board dimensions (3 x 3) and total stone count (9) are fixed constants. With k <= 8 empty squares, a raw permutation search visits at most k! <= 40,320 pairings, and branching by source square rather than individual stone merges identical stones in the same stack so the recursion makes at most 271 calls across all 24,310 valid boards (scanning 9 squares per call).
  • Space: O(1) auxiliary memory, using only a 3 x 3 copy of grid, a list of at most 8 empty coordinates, and a recursion stack at most 9 frames deep.

Edge cases

  • Already uniform (all 1s): empty_cells is empty, so fill_empty_cells(0) hits the base case right away and returns 0.
  • All 9 stones stacked on a single square: only one square satisfies count > 1, so every empty square draws from it; from a corner this costs 1 + 2 + 1 + 2 + 3 + 2 + 3 + 4 = 18, and from the center (1, 1) it costs 4 * 1 + 4 * 2 = 12.
  • Multiple extra stones stacked together (Example 2): checking counts[r][c] > 1 lets a square with 4 stones supply three distinct empty squares while retaining its final stone.
  • Tied distances: when two surplus squares sit equidistant from an empty square, backtracking explores both options so row/column scan order never biases the minimum.
  • Input immutability: copying grid into counts guarantees the caller's list of lists stays unmodified.

Common mistakes

  • Greedy nearest-neighbor pairing: matching each empty square to its closest remaining surplus stone fails on [[0, 2, 0], [1, 1, 1], [2, 1, 1]] (5 instead of 3).
  • Checking counts[r][c] > 0 instead of counts[r][c] > 1: a square holding 1 stone has zero surplus; letting it give away its stone leaves a new empty hole behind.
  • Forgetting counts[src_row][src_col] += 1 after recursion: without undoing the decrement on the way back up, later branches see missing stones and return wrong totals or inf.
  • Summing each empty square's distance to its closest surplus independently: two empty squares can pick the same lone extra stone, undercounting the true move cost.

Alternative approaches

  • Permutations of an expanded surplus list: repeat each (r, c) coordinate grid[r][c] - 1 times and test permutations against empty_cells in O(k! * k) time (<= 8! * 8 = 322,560 operations). Slightly more work when stones stack together, equally straightforward.
  • Bitmask dynamic programming: let dp[mask] store the minimum steps to fill the subset of empty squares marked in mask using the first popcount(mask) expanded surplus stones in O(k * 2^k) time (<= 8 * 256 = 2,048 operations).
  • Breadth-first search (BFS) over board states: treat the 9-tuple of stone counts as a graph vertex (24,310 reachable states) and expand single-stone moves outward from (1, 1, ..., 1). Great as an independent test oracle, though much slower and tied to tiny boards.

Follow-up questions

  • If the board scaled to N x N with N^2 stones, what polynomial-time graph algorithm replaces backtracking? The problem becomes minimum-weight bipartite matching (pairing items between two equal-sized sets to minimize summed edge cost). With k surplus stones and k empty squares, running the Hungarian algorithm (a primal-dual assignment solver on a k x k cost matrix) takes O(k^3) time. Alternatively, formulate the board directly as a minimum-cost flow network (a directed graph with edge capacities and per-unit shipping costs where supply is routed to demand at minimum expense): wire a super-source to each cell having count > 1 with capacity count - 1 and cost 0, connect edge-adjacent board cells with infinite capacity and cost 1, and wire each empty cell to a super-sink with capacity 1 and cost 0. Pushing k units of flow via successive shortest augmenting paths with Dijkstra runs in O(k * N^2 log N) time.
  • Why don't moving stones ever block each other or require detours longer than the Manhattan distance? Because intermediate squares have unlimited capacity, two stones never collide or deadlock in narrow passages, so any stone paired from (r1, c1) to (r2, c2) can walk an unobstructed shortest grid path of |r1 - r2| + |c1 - c2| steps. Conversely, each legal step shifts a single stone's row or column by 1, so no move sequence can beat the summed Manhattan distances of its net stone pairing, and by the triangle inequality (walking straight from A to E is never longer than relaying A -> M and M -> E) non-surplus stones never need to move at all.
  • How would you modify the solver to return a valid step-by-step list of adjacent transfers instead of just the move count? Have fill_empty_cells return (min_moves, best_pairs), where best_pairs records the winning ((src_row, src_col), (target_row, target_col)) pairings. Then replay each pair from start to finish one stone at a time: walk one stone vertically from src_row to target_row and horizontally from src_col to target_col, recording every single-cell hop (r1, c1) -> (r2, c2). Completing each trip in full is guaranteed valid in any pair order because src starts the trip with at least 2 stones and every intermediate square temporarily gains +1 stone right before forwarding it onward.

Follow-up questions

Similar questions

More American interview questions

All 5 American questions →