Complexity Analysis plus Jigsaw and 2048 Game Design

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Problem Statement

This multi-part software engineering exercise covers one complexity-analysis discussion prompt and two object-oriented game implementations.

Part 1 — Analyzing Code & Asymptotic Bounds (Prose)

Outline a clear, repeatable approach for reading unfamiliar short code fragments: state in plain English what result a snippet computes, derive tight Big-O time and auxiliary space bounds, and call out key cost assumptions (such as what the input-size variables represent and whether hash operations are average-case or worst-case).

Part 2 — Jigsaw Puzzle Engine (Edge, Piece, JigsawBoard)

Model a rectangular jigsaw puzzle where square pieces have four edges ordered clockwise (TOP = 0, RIGHT = 1, BOTTOM = 2, LEFT = 3) and edge kinds FLAT = "flat", TAB = "tab", BLANK = "blank":

@dataclass(frozen=True)
class Edge:
    kind: str
    shape: int = 0
    def fits(self, other: "Edge") -> bool: ...

class Piece:
    def __init__(self, piece_id: int, edges: List[Edge]): ...
    def rotate(self, turns: int = 1) -> None: ...
    def edge(self, side: int) -> Edge: ...

class JigsawBoard:
    def __init__(self, rows: int, cols: int): ...
    def can_place(self, piece: Piece, row: int, col: int) -> bool: ...
    def place(self, piece: Piece, row: int, col: int) -> bool: ...
    def remove(self, row: int, col: int) -> Optional[Piece]: ...
    def piece_at(self, row: int, col: int) -> Optional[Piece]: ...
    def is_complete(self) -> bool: ...
  • Edge.fits(other): Return True if and only if one edge is TAB and the other is BLANK with matching shape (FLAT edges never interlock with any edge).
  • Piece(piece_id, edges): Store the 4 edges at orientation 0 in [TOP, RIGHT, BOTTOM, LEFT] order (raise ValueError if len(edges) != 4). rotate(turns=1) rotates clockwise by 90 * turns degrees (negative turns rotate counterclockwise), and edge(side) returns whichever Edge currently faces side.
  • JigsawBoard:
    • can_place(piece, row, col) returns True iff (row, col) is in bounds and unoccupied, piece.piece_id is not already placed elsewhere on the board, every side facing outside the board boundary is FLAT, every side facing an interior neighbor cell is non-FLAT, and every side touching an already-placed neighbor satisfies fits against that neighbor's facing edge.
    • place(piece, row, col) places piece when can_place holds and returns whether placement succeeded.
    • remove(row, col) removes and returns the piece at (row, col) (or None if empty or out of bounds); piece_at(row, col) inspects without removing.
    • is_complete() returns True iff every cell holds a piece and all boundary rules and neighbor joints currently remain satisfied.

Part 3 — 2048 Game Engine (slide_line, Game2048)

Implement the core mechanics of 2048 across DIRECTIONS = ("left", "right", "up", "down"):

def slide_line(line: List[int]) -> Tuple[List[int], int]: ...

class Game2048:
    def __init__(self, size: int = 4, seed: Optional[int] = None,
                 board: Optional[List[List[int]]] = None): ...
    def move(self, direction: str) -> bool: ...
    def spawn_tile(self) -> Optional[Tuple[int, int]]: ...
    def is_game_over(self) -> bool: ...
  • slide_line(line): Shift non-zero numbers toward index 0 (0 marks an empty cell), fuse equal adjacent numbers at most once per turn starting from index 0, pad trailing 0s to keep len(line) unchanged, and return (new_line, points_earned) where points_earned sums the values of newly created merged tiles.
  • Game2048:
    • Expose self.score (starting at 0) and self.board (copied row-by-row from board when supplied; otherwise initialized to an empty size x size grid followed by two spawn_tile() calls). Seed a dedicated RNG with seed so spawns are reproducible.
    • move(direction) slides and merges every row or column toward direction (raising ValueError if direction is invalid). If at least one cell changed, add the merged points to self.score, call spawn_tile() once, and return True; otherwise change nothing and return False.
    • spawn_tile() places 2 (probability 0.9) or 4 (probability 0.1) on a uniformly chosen empty cell and returns (row, col), or None if no empty cell remains.
    • is_game_over() returns True iff no cell equals 0 and no two horizontally or vertically adjacent cells hold equal values.

Examples

Example 1 (Part 2 — Jigsaw Placement & Rotation)

board = JigsawBoard(1, 2)
left_piece = Piece(10, [Edge(FLAT), Edge(TAB, 5), Edge(FLAT), Edge(FLAT)])
right_piece = Piece(20, [Edge(BLANK, 5), Edge(FLAT), Edge(FLAT), Edge(FLAT)])

board.place(left_piece, 0, 0)      # -> True
board.can_place(right_piece, 0, 1) # -> False (BLANK(5) faces top border; FLAT faces left_piece)
right_piece.rotate(-1)             # 90 deg counterclockwise moves TOP's BLANK(5) to LEFT
board.place(right_piece, 0, 1)     # -> True
board.is_complete()                # -> True

Walk-through: left_piece has FLAT on its three outer borders and TAB(5) facing (0, 1). Initially right_piece has BLANK(5) on TOP, which violates both the top border rule and the interior joint rule. Rotating right_piece by -1 shifts BLANK(5) onto LEFT, matching TAB(5) and completing the 1 x 2 puzzle.

Example 2 (Part 3 — 2048 Single-Merge Rule & Directional Swipe)

slide_line([4, 0, 4, 4])  # -> ([8, 4, 0, 0], 8)

start_grid = [
    [0, 4, 4, 8],
    [2, 0, 0, 2],
    [0, 0, 0, 0],
    [4, 4, 4, 4],
]
game = Game2048(board=start_grid, seed=7)
game.move("right")        # -> True, game.score == 28

Walk-through: Swiping "right" processes each row starting from the right wall: - Row 0 ([0, 4, 4, 8]): 8 stays at column 3 while the two 4s merge into 8 at column 2 (+8 points), yielding [0, 0, 8, 8] without chain-merging into 16. - Row 1 ([2, 0, 0, 2]): merges into [0, 0, 0, 4] (+4 points). - Row 3 ([4, 4, 4, 4]): forms two separate 8s [0, 0, 8, 8] (+16 points). game.score increases by 8 + 4 + 16 = 28, and one 2 or 4 spawns in an empty cell.

Constraints

  • rows >= 1 and cols >= 1 for JigsawBoard; turns in Piece.rotate(turns) may be any negative, zero, or positive integer.
  • size >= 2 for Game2048; empty cells contain 0 and occupied cells contain positive powers of 2.
  • Passing an initial board to Game2048 must not mutate the caller's list when moves occur.

Step-by-step walkthrough

  1. Part 1: Step-by-step recipe for code comprehension and Big-O

    Note: the original statement omits the two specific code snippets. Here is a repeatable 6-step framework you can apply to any snippet an interviewer hands you, followed by two classic worked examples in the next step.

    Whenever you are asked to explain an unfamiliar snippet and analyze its asymptotic cost, walk through these six steps out loud instead of guessing:

    1. Define the input-size variables explicitly: Clarify what n (and m, if present) measures — list length, character count, tree node count, or the magnitude of an integer.
    2. Trace a tiny concrete input (3–4 items) and summarize the goal in one sentence: Never narrate code line by line ("set i to 0, then loop while i < n..."). Trace [3, 1, 3], observe the output, and state the purpose ("Returns True iff the sequence contains a repeated value").
    3. Sum dependent loop iterations instead of blindly multiplying: Two independent 0..n loops multiply to O(n^2), whereas an inner loop bounded by the outer variable (for j in range(i) or while i < n: ... i *= 2) requires summing the work across rounds.
    4. Spot hidden O(n) costs inside single expressions: Watch for x in a_list (O(n) linear scan), arr[:k] slicing (O(k) copy), list.pop(0) (O(n) shift), sorted(...) (O(n log n)), and repeated string += inside loops.
    5. Separate auxiliary space from input size: Count newly allocated hash sets, dictionaries, lists, slices, and the deepest call-stack frame depth of recursive calls.
    6. State cost assumptions clearly: Note O(1) expected vs O(n) worst-case hashing, fixed-width O(1) arithmetic, and best/average/worst cases when early exits exist.
  2. Part 1: Worked complexity analysis on two classic snippets

    Snippet A: Early-exit duplicate check with a hash set

    def has_duplicate(nums):
        seen = set()
        for x in nums:
            if x in seen:
                return True
            seen.add(x)
        return False
    
    • Plain-English summary: Determines whether any value appears at least twice in nums, returning True at the first repeat and False when all elements are distinct.
    • Time complexity: With n = len(nums), the loop performs at most n hash membership checks and insertions. Under O(1) average hashing, runtime is O(n) expected (best case O(1) when nums[0] == nums[1]; worst case O(n^2) only under adversarial hash collisions).
    • Space complexity: O(n) auxiliary space in the worst case when all n items are unique and stored in seen.

    Snippet B: Doubling outer loop — the classic O(n) vs O(n log n) trap

    def count_steps(n):
        total = 0
        i = 1
        while i < n:
            for _ in range(i):
                total += 1
            i *= 2
        return total
    
    • Plain-English summary: Sums every power of 2 strictly below n (1 + 2 + 4 + ...). When n = 10, i visits 1, 2, 4, 8 and returns 15.
    • Time complexity: Multiplying "outer runs log2(n) times" by "inner runs up to n times" gives a loose O(n log n) bound. Summing the actual inner counts reveals the tight bound:
    Round:        1    2    3   ...   k        (where 2^(k-1) < n <= 2^k)
    Inner steps:  1  + 2  + 4 + ... + 2^(k-1)  =  2^k - 1  <  2n
    

    Because each round doubles the previous one, all earlier rounds combined total less than the single final round (1 + 2 + 4 = 7 < 8). Since 2^(k-1) < n, total iterations stay strictly below 2n, giving tight runtime O(n) (Theta(n)). - Space complexity: O(1) auxiliary space for two integer variables total and i.

  3. Part 2: Model Jigsaw edges and O(1) piece rotation

    Now let's build Edge, Piece, and JigsawBoard. Each piece has 4 sides (TOP = 0, RIGHT = 1, BOTTOM = 2, LEFT = 3 clockwise) and rotates in 90-degree increments:

    • Edge(kind, shape): An immutable value object (@dataclass(frozen=True)). kind is FLAT (straight border), TAB (outward knob), or BLANK (inward socket), and shape identifies the cut profile so fits returns True iff one is TAB, the other is BLANK, and their shape integers match.
    • Piece(piece_id, edges): Keeps its 4 initial edges [E0, E1, E2, E3] fixed at rotation = 0, alongside an orientation counter self.rotation in {0, 1, 2, 3}.

    Why does edge(side) index (side - self.rotation) % 4? Watch 1 clockwise turn (self.rotation = 1):

       At rotation = 0:                After 1 clockwise turn (rotation = 1):
             E0 (TOP=0)                              E3 (now at TOP=0!)
           +------------+                          +------------+
    E3     |            | E1                E2     |            | E0
    (LEFT  |   Piece    | (RIGHT            (LEFT  |   Piece    | (RIGHT
     =3)   |            |  =1)               =3)   |            |  =1)
           +------------+                          +------------+
             E2 (BOTTOM=2)                           E1 (BOTTOM=2)
    

    One clockwise turn brings old LEFT (3) into TOP (0) ((0 - 1) % 4 = 3), old TOP (0) into RIGHT (1) ((1 - 1) % 4 = 0), and in general self.edges[(side - self.rotation) % 4] in O(1) time without shifting arrays!

    from typing import List, Optional, Tuple
    from dataclasses import dataclass
    
    FLAT, TAB, BLANK = "flat", "tab", "blank"
    TOP, RIGHT, BOTTOM, LEFT = 0, 1, 2, 3  # sides numbered in clockwise order
    
    # (row_delta, col_delta) to step from (row, col) to the neighbor facing each side.
    STEP = {TOP: (-1, 0), RIGHT: (0, 1), BOTTOM: (1, 0), LEFT: (0, -1)}
    
    
    def opposite(side: int) -> int:
        # Two clockwise steps turn TOP(0)<->BOTTOM(2) and RIGHT(1)<->LEFT(3).
        return (side + 2) % 4
    
    
    @dataclass(frozen=True)
    class Edge:
        """One side of a jigsaw piece: kind is FLAT, TAB, or BLANK; shape matches cuts."""
        kind: str
        shape: int = 0
    
        def fits(self, other: "Edge") -> bool:
            # Two edges interlock only when they share the same cut shape AND one is TAB while
            # the other is BLANK (two FLAT border edges never interlock with each other).
            if self.shape != other.shape:
                return False
            is_tab_and_blank = self.kind == TAB and other.kind == BLANK
            is_blank_and_tab = self.kind == BLANK and other.kind == TAB
            return is_tab_and_blank or is_blank_and_tab
    
    
    class Piece:
        def __init__(self, piece_id: int, edges: List[Edge]):
            if len(edges) != 4:
                raise ValueError("a piece has exactly 4 edges")
            self.piece_id = piece_id
            # self.edges: [TOP, RIGHT, BOTTOM, LEFT] edges fixed at rotation 0.
            self.edges = list(edges)
            # self.rotation: number of 90-degree clockwise turns in {0, 1, 2, 3}.
            self.rotation = 0
    
        def rotate(self, turns: int = 1) -> None:
            # Modulo 4 wraps both positive (clockwise) and negative (counterclockwise) turns into 0..3.
            self.rotation = (self.rotation + turns) % 4
    
        def edge(self, side: int) -> Edge:
            # One clockwise turn moves old LEFT(3) into TOP(0), old TOP(0) into RIGHT(1), etc.,
            # so the edge now facing `side` came from original index `(side - self.rotation) % 4`.
            original_index = (side - self.rotation) % 4
            return self.edges[original_index]
    
  4. Part 2: Validate placements, removals, and board completion

    JigsawBoard stores a rows x cols grid plus self.position (piece_id -> (row, col)) for O(1) duplicate-piece checks. can_place(piece, row, col) checks four conditions:

    1. (row, col) lies inside the grid and is currently None.
    2. piece.piece_id is not already on the board.
    3. Every side facing outside the grid boundary is FLAT, and every side facing another grid cell is not FLAT.
    4. Every already-placed neighbor satisfies my_edge.fits(neighbor.edge(opposite(side))).

    Notice why is_complete() re-checks _fits_here on every cell instead of merely checking len(self.position) == rows * cols: because Piece is mutable, rotating an already-placed piece in place would break joints without changing len(self.position)!

    class JigsawBoard:
        def __init__(self, rows: int, cols: int):
            self.rows = rows
            self.cols = cols
            # self.grid: rows x cols 2D table of placed Piece objects (or None for empty cells).
            self.grid: List[List[Optional[Piece]]] = []
            for _ in range(rows):
                self.grid.append([None] * cols)
            # self.position: maps placed piece_id -> (row, col) for O(1) duplicate-placement checks.
            self.position = {}
    
        def _inside(self, row: int, col: int) -> bool:
            return 0 <= row < self.rows and 0 <= col < self.cols
    
        def _fits_here(self, piece: Piece, row: int, col: int) -> bool:
            """Verify all four sides of `piece` against board borders and placed neighbors."""
            for side in (TOP, RIGHT, BOTTOM, LEFT):
                d_row, d_col = STEP[side]
                neighbor_row = row + d_row
                neighbor_col = col + d_col
                my_edge = piece.edge(side)
    
                if not self._inside(neighbor_row, neighbor_col):
                    # Outer border of the puzzle: only a straight FLAT edge is valid here.
                    if my_edge.kind != FLAT:
                        return False
                    continue
    
                # Interior joint inside the board: a straight FLAT edge cannot face another cell.
                if my_edge.kind == FLAT:
                    return False
    
                neighbor = self.grid[neighbor_row][neighbor_col]
                if neighbor is not None:
                    facing_edge = neighbor.edge(opposite(side))
                    if not my_edge.fits(facing_edge):
                        return False
            return True
    
        def can_place(self, piece: Piece, row: int, col: int) -> bool:
            if not self._inside(row, col) or self.grid[row][col] is not None:
                return False
            if piece.piece_id in self.position:
                return False
            return self._fits_here(piece, row, col)
    
        def place(self, piece: Piece, row: int, col: int) -> bool:
            if not self.can_place(piece, row, col):
                return False
            self.grid[row][col] = piece
            self.position[piece.piece_id] = (row, col)
            return True
    
        def remove(self, row: int, col: int) -> Optional[Piece]:
            if not self._inside(row, col) or self.grid[row][col] is None:
                return None
            piece = self.grid[row][col]
            self.grid[row][col] = None
            del self.position[piece.piece_id]
            return piece
    
        def piece_at(self, row: int, col: int) -> Optional[Piece]:
            if not self._inside(row, col):
                return None
            return self.grid[row][col]
    
        def is_complete(self) -> bool:
            # Re-validate every cell (not just count == rows * cols) in case a placed Piece
            # object was rotated in place after `place()` put it on the board.
            for row in range(self.rows):
                for col in range(self.cols):
                    piece = self.grid[row][col]
                    if piece is None or not self._fits_here(piece, row, col):
                        return False
            return True
    
  5. Part 3: Solve 2048 for a single line without double-merging

    Every direction in 2048 (left, right, up, down) runs the exact same 1D rule along size lines. Let's write slide_line(line) — sliding non-zero tiles toward index 0 — in three short phases:

    Input A (Example 2): [4, 0, 4, 4]
      Phase 1 (drop zeros):          [4, 4, 4]
      Phase 2 (merge pairs once):    i=0: 4==4 -> emit 8 (+8 pts), jump i += 2!
                                     i=2: emit 4, advance i += 1
                                     -> [8, 4]
      Phase 3 (pad zeros to len 4):  [8, 4, 0, 0], points = 8
    
    Input B (Example 2 row 0 from right wall): [8, 4, 4, 0]
      Phase 1 (drop zeros):          [8, 4, 4]
      Phase 2 (merge pairs once):    i=0: 8!=4 -> emit 8, advance i += 1
                                     i=1: 4==4 -> emit 8 (+8 pts), jump i += 2!
      Phase 3 (pad zeros to len 4):  [8, 8, 0, 0], points = 8  (NOT [16, 0, 0, 0]!)
    
    DIRECTIONS = ("left", "right", "up", "down")
    
    
    def slide_line(line: List[int]) -> Tuple[List[int], int]:
        # Phase 1: squeeze out empty cells (zeros) while preserving tile order.
        non_zero: List[int] = []
        for value in line:
            if value != 0:
                non_zero.append(value)
    
        # Phase 2: walk from the target wall (index 0) outward, merging equal adjacent tiles once.
        merged_line: List[int] = []
        points = 0
        i = 0
        while i < len(non_zero):
            if i + 1 < len(non_zero) and non_zero[i] == non_zero[i + 1]:
                merged_value = non_zero[i] * 2
                merged_line.append(merged_value)
                points += merged_value
                # Advance by 2 so neither consumed tile (nor the new merged tile) merges again!
                i += 2
            else:
                merged_line.append(non_zero[i])
                i += 1
    
        # Phase 3: pad trailing zeros back to the original line length.
        while len(merged_line) < len(line):
            merged_line.append(0)
        return merged_line, points
    
  6. Part 3: Generalize to all four directions, tile spawning, and game over

    Instead of writing four directional merge loops, _line_cells(direction, index) returns the (row, col) coordinates of row or column index ordered starting at the wall tiles move toward:

    direction == "left":   row `index`, col 0 -> 1 -> 2 -> 3   (left wall is index 0)
    direction == "right":  row `index`, col 3 -> 2 -> 1 -> 0   (right wall is index 0!)
    direction == "up":     col `index`, row 0 -> 1 -> 2 -> 3   (top wall is index 0)
    direction == "down":   col `index`, row 3 -> 2 -> 1 -> 0   (bottom wall is index 0!)
    

    We gather old_line along cells, run slide_line(old_line), and write new_line back along those same cells: 1. Blocked-move guard: Only if at least one line changed (new_line != old_line) do we add gained_points to self.score and invoke self.spawn_tile(). 2. Deterministic spawning: Use a private self.rng = random.Random(seed) to place 2 (0.9 probability) or 4 (0.1 probability) on a random empty cell. 3. Game-over check: Legal moves still exist iff any cell is 0 OR any cell equals its right neighbor (col + 1) or bottom neighbor (row + 1).

    import random
    
    
    class Game2048:
        def __init__(self, size: int = 4, seed: Optional[int] = None,
                     board: Optional[List[List[int]]] = None):
            # Private Random instance keeps spawns deterministic without touching global random state.
            self.rng = random.Random(seed)
            self.score = 0
    
            if board is not None:
                self.size = len(board)
                # Copy each row so game moves never mutate the caller's input list.
                self.board = []
                for row in board:
                    self.board.append(list(row))
            else:
                self.size = size
                self.board = []
                for _ in range(size):
                    self.board.append([0] * size)
                self.spawn_tile()
                self.spawn_tile()
    
        def _line_cells(self, direction: str, index: int) -> List[Tuple[int, int]]:
            """Coordinates of row/col `index` ordered starting AT the wall tiles move toward."""
            cells: List[Tuple[int, int]] = []
            for k in range(self.size):
                if direction == "left":
                    cells.append((index, k))
                elif direction == "right":
                    cells.append((index, self.size - 1 - k))
                elif direction == "up":
                    cells.append((k, index))
                else:  # "down"
                    cells.append((self.size - 1 - k, index))
            return cells
    
        def move(self, direction: str) -> bool:
            if direction not in DIRECTIONS:
                raise ValueError("unknown direction: " + repr(direction))
    
            changed = False
            gained_points = 0
    
            # Slide every row (or column) toward `direction` using `slide_line`.
            for index in range(self.size):
                cells = self._line_cells(direction, index)
                old_line = []
                for row, col in cells:
                    old_line.append(self.board[row][col])
    
                new_line, line_points = slide_line(old_line)
                gained_points += line_points
    
                if new_line != old_line:
                    changed = True
                    for k in range(self.size):
                        row, col = cells[k]
                        self.board[row][col] = new_line[k]
    
            # A blocked move that changes no cell must NOT add points or spawn a new tile.
            if not changed:
                return False
    
            self.score += gained_points
            self.spawn_tile()
            return True
    
        def empty_cells(self) -> List[Tuple[int, int]]:
            cells: List[Tuple[int, int]] = []
            for row in range(self.size):
                for col in range(self.size):
                    if self.board[row][col] == 0:
                        cells.append((row, col))
            return cells
    
        def spawn_tile(self) -> Optional[Tuple[int, int]]:
            empty = self.empty_cells()
            if not empty:
                return None
            row, col = self.rng.choice(empty)
            # Standard 2048 spawn distribution: 90% chance of 2, 10% chance of 4.
            if self.rng.random() < 0.9:
                self.board[row][col] = 2
            else:
                self.board[row][col] = 4
            return row, col
    
        def is_game_over(self) -> bool:
            # Game continues if ANY empty cell exists OR ANY horizontal/vertical pair matches.
            for row in range(self.size):
                for col in range(self.size):
                    value = self.board[row][col]
                    if value == 0:
                        return False
                    if col + 1 < self.size and self.board[row][col + 1] == value:
                        return False
                    if row + 1 < self.size and self.board[row + 1][col] == value:
                        return False
            return True
    
  7. Walk through Examples 1 and 2 end to end

    Walk-through of Example 1 (1 x 2 JigsawBoard): - left_piece ([TOP=FLAT, RIGHT=TAB(5), BOTTOM=FLAT, LEFT=FLAT]) goes into (0, 0) cleanly because its three outer sides are FLAT and its interior RIGHT side is TAB(5). - right_piece starts as [TOP=BLANK(5), RIGHT=FLAT, BOTTOM=FLAT, LEFT=FLAT]. At (0, 1), TOP faces outside the board (BLANK(5) != FLAT) and LEFT faces (0, 0) (FLAT inside the board), so can_place returns False. - Calling right_piece.rotate(-1) sets self.rotation = 3: now LEFT (3) reads edges[(3 - 3) % 4] = BLANK(5) (which interlocks with left_piece's TAB(5)!) and TOP, RIGHT, BOTTOM read FLAT, so place(right_piece, 0, 1) and is_complete() both return True.

    Walk-through of Example 2 (move("right") on Game2048):

    Board before move("right"):         Read from right wall -> slide_line -> write back:
      0  4  4  8   (row 0)              [8, 4, 4, 0] -> [8, 8, 0, 0] (+8)  ->  0  0  8  8
      2  0  0  2   (row 1)              [2, 0, 0, 2] -> [4, 0, 0, 0] (+4)  ->  0  0  0  4
      0  0  0  0   (row 2)              [0, 0, 0, 0] -> [0, 0, 0, 0] (+0)  ->  0  0  0  0
      4  4  4  4   (row 3)              [4, 4, 4, 4] -> [8, 8, 0, 0] (+16) ->  0  0  8  8
    

    Row 0 proves why slide_line never chain-merges [8, 4, 4] into 16, while row 3 merges two separate pairs of 4s for +16. Total score rises to 28, and one 2 or 4 spawns in an empty cell.

  8. Complete solution

    from typing import List, Optional, Tuple
    from dataclasses import dataclass
    import random
    
    # ---------------------------------------------------------------------------
    # Part 2: Jigsaw puzzle
    # ---------------------------------------------------------------------------
    
    FLAT, TAB, BLANK = "flat", "tab", "blank"
    TOP, RIGHT, BOTTOM, LEFT = 0, 1, 2, 3  # sides numbered in clockwise order
    
    # (row_delta, col_delta) to step from (row, col) to the neighbor facing each side.
    STEP = {TOP: (-1, 0), RIGHT: (0, 1), BOTTOM: (1, 0), LEFT: (0, -1)}
    
    
    def opposite(side: int) -> int:
        # Two clockwise steps turn TOP(0)<->BOTTOM(2) and RIGHT(1)<->LEFT(3).
        return (side + 2) % 4
    
    
    @dataclass(frozen=True)
    class Edge:
        """One side of a jigsaw piece: kind is FLAT, TAB, or BLANK; shape matches cuts."""
        kind: str
        shape: int = 0
    
        def fits(self, other: "Edge") -> bool:
            # Two edges interlock only when they share the same cut shape AND one is TAB while
            # the other is BLANK (two FLAT border edges never interlock with each other).
            if self.shape != other.shape:
                return False
            is_tab_and_blank = self.kind == TAB and other.kind == BLANK
            is_blank_and_tab = self.kind == BLANK and other.kind == TAB
            return is_tab_and_blank or is_blank_and_tab
    
    
    class Piece:
        def __init__(self, piece_id: int, edges: List[Edge]):
            if len(edges) != 4:
                raise ValueError("a piece has exactly 4 edges")
            self.piece_id = piece_id
            # self.edges: [TOP, RIGHT, BOTTOM, LEFT] edges fixed at rotation 0.
            self.edges = list(edges)
            # self.rotation: number of 90-degree clockwise turns in {0, 1, 2, 3}.
            self.rotation = 0
    
        def rotate(self, turns: int = 1) -> None:
            # Modulo 4 wraps both positive (clockwise) and negative (counterclockwise) turns into 0..3.
            self.rotation = (self.rotation + turns) % 4
    
        def edge(self, side: int) -> Edge:
            # One clockwise turn moves old LEFT(3) into TOP(0), old TOP(0) into RIGHT(1), etc.,
            # so the edge now facing `side` came from original index `(side - self.rotation) % 4`.
            original_index = (side - self.rotation) % 4
            return self.edges[original_index]
    
    
    class JigsawBoard:
        def __init__(self, rows: int, cols: int):
            self.rows = rows
            self.cols = cols
            # self.grid: rows x cols 2D table of placed Piece objects (or None for empty cells).
            self.grid: List[List[Optional[Piece]]] = []
            for _ in range(rows):
                self.grid.append([None] * cols)
            # self.position: maps placed piece_id -> (row, col) for O(1) duplicate-placement checks.
            self.position = {}
    
        def _inside(self, row: int, col: int) -> bool:
            return 0 <= row < self.rows and 0 <= col < self.cols
    
        def _fits_here(self, piece: Piece, row: int, col: int) -> bool:
            """Verify all four sides of `piece` against board borders and placed neighbors."""
            for side in (TOP, RIGHT, BOTTOM, LEFT):
                d_row, d_col = STEP[side]
                neighbor_row = row + d_row
                neighbor_col = col + d_col
                my_edge = piece.edge(side)
    
                if not self._inside(neighbor_row, neighbor_col):
                    # Outer border of the puzzle: only a straight FLAT edge is valid here.
                    if my_edge.kind != FLAT:
                        return False
                    continue
    
                # Interior joint inside the board: a straight FLAT edge cannot face another cell.
                if my_edge.kind == FLAT:
                    return False
    
                neighbor = self.grid[neighbor_row][neighbor_col]
                if neighbor is not None:
                    facing_edge = neighbor.edge(opposite(side))
                    if not my_edge.fits(facing_edge):
                        return False
            return True
    
        def can_place(self, piece: Piece, row: int, col: int) -> bool:
            if not self._inside(row, col) or self.grid[row][col] is not None:
                return False
            if piece.piece_id in self.position:
                return False
            return self._fits_here(piece, row, col)
    
        def place(self, piece: Piece, row: int, col: int) -> bool:
            if not self.can_place(piece, row, col):
                return False
            self.grid[row][col] = piece
            self.position[piece.piece_id] = (row, col)
            return True
    
        def remove(self, row: int, col: int) -> Optional[Piece]:
            if not self._inside(row, col) or self.grid[row][col] is None:
                return None
            piece = self.grid[row][col]
            self.grid[row][col] = None
            del self.position[piece.piece_id]
            return piece
    
        def piece_at(self, row: int, col: int) -> Optional[Piece]:
            if not self._inside(row, col):
                return None
            return self.grid[row][col]
    
        def is_complete(self) -> bool:
            # Re-validate every cell (not just count == rows * cols) in case a placed Piece
            # object was rotated in place after `place()` put it on the board.
            for row in range(self.rows):
                for col in range(self.cols):
                    piece = self.grid[row][col]
                    if piece is None or not self._fits_here(piece, row, col):
                        return False
            return True
    
    
    # ---------------------------------------------------------------------------
    # Part 3: 2048
    # ---------------------------------------------------------------------------
    
    DIRECTIONS = ("left", "right", "up", "down")
    
    
    def slide_line(line: List[int]) -> Tuple[List[int], int]:
        # Phase 1: squeeze out empty cells (zeros) while preserving tile order.
        non_zero: List[int] = []
        for value in line:
            if value != 0:
                non_zero.append(value)
    
        # Phase 2: walk from the target wall (index 0) outward, merging equal adjacent tiles once.
        merged_line: List[int] = []
        points = 0
        i = 0
        while i < len(non_zero):
            if i + 1 < len(non_zero) and non_zero[i] == non_zero[i + 1]:
                merged_value = non_zero[i] * 2
                merged_line.append(merged_value)
                points += merged_value
                # Advance by 2 so neither consumed tile (nor the new merged tile) merges again!
                i += 2
            else:
                merged_line.append(non_zero[i])
                i += 1
    
        # Phase 3: pad trailing zeros back to the original line length.
        while len(merged_line) < len(line):
            merged_line.append(0)
        return merged_line, points
    
    
    class Game2048:
        def __init__(self, size: int = 4, seed: Optional[int] = None,
                     board: Optional[List[List[int]]] = None):
            # Private Random instance keeps spawns deterministic without touching global random state.
            self.rng = random.Random(seed)
            self.score = 0
    
            if board is not None:
                self.size = len(board)
                # Copy each row so game moves never mutate the caller's input list.
                self.board = []
                for row in board:
                    self.board.append(list(row))
            else:
                self.size = size
                self.board = []
                for _ in range(size):
                    self.board.append([0] * size)
                self.spawn_tile()
                self.spawn_tile()
    
        def _line_cells(self, direction: str, index: int) -> List[Tuple[int, int]]:
            """Coordinates of row/col `index` ordered starting AT the wall tiles move toward."""
            cells: List[Tuple[int, int]] = []
            for k in range(self.size):
                if direction == "left":
                    cells.append((index, k))
                elif direction == "right":
                    cells.append((index, self.size - 1 - k))
                elif direction == "up":
                    cells.append((k, index))
                else:  # "down"
                    cells.append((self.size - 1 - k, index))
            return cells
    
        def move(self, direction: str) -> bool:
            if direction not in DIRECTIONS:
                raise ValueError("unknown direction: " + repr(direction))
    
            changed = False
            gained_points = 0
    
            # Slide every row (or column) toward `direction` using `slide_line`.
            for index in range(self.size):
                cells = self._line_cells(direction, index)
                old_line = []
                for row, col in cells:
                    old_line.append(self.board[row][col])
    
                new_line, line_points = slide_line(old_line)
                gained_points += line_points
    
                if new_line != old_line:
                    changed = True
                    for k in range(self.size):
                        row, col = cells[k]
                        self.board[row][col] = new_line[k]
    
            # A blocked move that changes no cell must NOT add points or spawn a new tile.
            if not changed:
                return False
    
            self.score += gained_points
            self.spawn_tile()
            return True
    
        def empty_cells(self) -> List[Tuple[int, int]]:
            cells: List[Tuple[int, int]] = []
            for row in range(self.size):
                for col in range(self.size):
                    if self.board[row][col] == 0:
                        cells.append((row, col))
            return cells
    
        def spawn_tile(self) -> Optional[Tuple[int, int]]:
            empty = self.empty_cells()
            if not empty:
                return None
            row, col = self.rng.choice(empty)
            # Standard 2048 spawn distribution: 90% chance of 2, 10% chance of 4.
            if self.rng.random() < 0.9:
                self.board[row][col] = 2
            else:
                self.board[row][col] = 4
            return row, col
    
        def is_game_over(self) -> bool:
            # Game continues if ANY empty cell exists OR ANY horizontal/vertical pair matches.
            for row in range(self.size):
                for col in range(self.size):
                    value = self.board[row][col]
                    if value == 0:
                        return False
                    if col + 1 < self.size and self.board[row][col + 1] == value:
                        return False
                    if row + 1 < self.size and self.board[row + 1][col] == value:
                        return False
            return True
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

All three parts reward the same design instinct: collapse repetitive cases into one small, testable rule. - In Part 1 (Big-O analysis), counting runtime works like adding a receipt: when an inner loop's bound depends on the outer loop (1 + 2 + 4 + 8), sum the actual line items (15 < 2n) instead of multiplying the number of outer steps by the largest step (4 * 8 = 32). - In Part 2 (Jigsaw puzzle), rather than rearranging a piece's four edges in memory every time a player rotates it, keep the four Edge objects fixed and update one orientation dial (self.rotation in 0..3), checking only the four sides around a target cell on placement. - In Part 3 (2048), swiping left, right, up, or down is one 1D conveyor-belt rule viewed from whichever wall the player swiped toward: pull non-zero numbers toward index 0 and merge equal neighbors while advancing i += 2 so no tile merges twice in a single move.

Why do ad-hoc implementations tangle up so easily? Writing four separate directional loops in 2048 quadruples index-order bugs and lets chain-merge bugs ([0, 4, 4, 8] -> [0, 0, 0, 16]) slip in. Similarly, in Jigsaw, testing edge equality (==) instead of complementary TAB/BLANK matching — or forgetting that FLAT edges belong exclusively on the outer board boundary — accepts impossible placements.

Let's trace Example 1's rotation in Jigsaw and Example 2's row 0 swipe in 2048 side by side:

Jigsaw 90-deg counterclockwise turn (`right_piece.rotate(-1)` -> rotation = 3):
  edges at rotation 0 = [TOP=BLANK(5), RIGHT=FLAT, BOTTOM=FLAT, LEFT=FLAT]
  LEFT(3) now reads edges[(3 - 3) % 4] = BLANK(5), interlocking with left_piece's TAB(5)!

2048 Example 2 row 0 `[0, 4, 4, 8]` swiped `"right"`:
  1. Read starting AT the right wall: [8, 4, 4, 0]
  2. Drop zeros -> [8, 4, 4] -> keep 8, merge 4+4 (+8 pts, jump i += 2) -> [8, 8, 0, 0]
  3. Write back from the right wall:  [0, 0, 8, 8]  (no chain merge into 16!)

Complexity

Part 1 (worked complexity snippets): - Hash-set duplicate check: O(n) expected time because we scan n items once with O(1) average hash-set lookups and inserts (O(n^2) worst case only under pathological hash collisions), and O(n) auxiliary space for up to n distinct elements. - Doubling nested loop: O(n) (Theta(n)) time — the inner counts 1 + 2 + 4 + ... + 2^(k-1) form a geometric series (a sequence where each term multiplies the previous term by a constant ratio), whose sum 2^k - 1 is strictly less than 2n — and O(1) auxiliary space.

Part 2 (Jigsaw puzzle on an R x C board with P pieces): - Edge.fits, Piece.rotate, Piece.edge: O(1) time and O(1) space — Edge is an immutable value object (defined solely by its field values), and rotate updates one integer modulo 4. - can_place, place, remove, piece_at: O(1) average time — inspects at most 4 neighboring sides plus one O(1) hash lookup or update in self.position. - is_complete: O(R * C) time — visits every cell on the R x C grid and checks 4 sides per cell. - Space: O(R * C + P) for the R x C grid, P pieces of 4 edges each, and at most R * C entries in self.position.

Part 3 (2048 on an n x n board, with n = 4 in standard 2048): - slide_line (length n): O(n) time and O(n) temporary space — one linear pass removes zeros, a second merges adjacent pairs, and trailing zeros pad to length n. - move: O(n^2) time — applies slide_line across n lines of length n (O(n^2)) and scans n^2 cells in spawn_tile when the board changes. - is_game_over: O(n^2) time — scans all n^2 cells and compares at most 2 neighbors (right and down) per cell. - Space: O(n^2) for self.board (plus O(n^2) temporary coordinate/empty-cell lists during a move).

Edge cases

  • Jigsaw 1 x 1 board: All four sides sit on the outer border, so only a piece with four FLAT edges fits.
  • Rotating an already-placed Jigsaw piece: Because callers hold references to Piece instances, mutating p.rotate() after board.place(p, r, c) breaks joints; is_complete() detects this by re-evaluating _fits_here on every cell.
  • Negative and multi-turn rotations: rotate(-1) and rotate(5) wrap cleanly via (self.rotation + turns) % 4.
  • Placing the same Piece twice: Blocked in O(1) by piece.piece_id in self.position.
  • 2048 single-merge traps: [4, 0, 4, 4] produces [8, 4, 0, 0] (+8 points); [8, 4, 4, 0] produces [8, 8, 0, 0] (+8 points, never [16, 0, 0, 0]); [4, 4, 4, 4] produces [8, 8, 0, 0] (+16 points).
  • Blocked (no-op) 2048 swipe: When a move leaves every cell unchanged, move returns False, adds 0 points, and does not spawn a tile.
  • Full 2048 board with a surviving merge: Zero empty cells is not game over if any orthogonal pair of neighbors shares the same number.

Common mistakes

  • Part 1 — Multiplying dependent loop bounds: Reporting O(n log n) instead of O(n) on geometric series loops (1 + 2 + 4 + ... < 2n), or missing hidden O(n) operations like x in list_obj.
  • Part 2 — Using (side + self.rotation) % 4 instead of (side - self.rotation) % 4: Adding rotation turns edges counterclockwise while claiming clockwise; verify rotate(1) by checking that old LEFT (3) moves to TOP (0).
  • Part 2 — Checking only top and left neighbors in can_place: Interactive placement allows pieces in any order, so all 4 sides (plus border vs interior FLAT rules) must be checked.
  • Part 3 — Double-merging tiles in one turn: Stepping i += 1 or merging against merged_line[-1] turns [8, 4, 4, 0] into [16, 0, 0, 0].
  • Part 3 — Scanning "right" or "down" from index 0 instead of the target wall: Swiping [2, 0, 2, 2] right must yield [0, 0, 2, 4], not [0, 0, 4, 2].
  • Part 3 — Spawning on a blocked move or aliasing the caller's board: Always return False before spawn_tile() when not changed, and copy each row in __init__.

Alternative approaches

  • 2048 via matrix transformations: Implement only move_left(grid), then express right, up, and down via row reversal and matrix transpose around move_left. Very compact (O(n^2)), though it allocates several intermediate grids per move compared with _line_cells.
  • Signed-integer Jigsaw edges: Encode FLAT as 0, TAB of shape s as +s, and BLANK of shape s as -s, so two edges interlock iff e1 != 0 and e1 + e2 == 0.

Follow-up questions

  • How would you build an automated solver for JigsawBoard, and when does the search stay fast versus intractable? Fill the board row by row with backtracking (placing a candidate (piece, rotation), recursing to the next cell, and undoing via remove on dead ends), backed by a hash index mapping (required_top_edge, required_left_edge) to matching piece rotations. When every interior cut shape is unique, each cell has O(1) valid candidates so the entire puzzle solves in O(P) time; when many edges share repeated shapes, general edge-matching puzzles become NP-complete (problems with no known polynomial-time worst-case algorithm, requiring constraint-propagation pruning).
  • How can Game2048 support an undo() operation without letting players re-roll for luckier tile spawns? Right before applying each valid move (changed == True), push (board_copy, self.score, self.rng.getstate()) onto an undo stack. Calling undo() pops that snapshot and restores self.board, self.score, and self.rng.setstate(saved_state) — guaranteeing that replaying the same move reproduces the exact same spawned tile and cell in O(n^2) space per saved turn.
  • What is the cleanest strategy for unit-testing game mechanics that depend on random tile generation? Inject a controllable seed into a private random.Random(seed) instance (dependency injection — passing collaborators in rather than relying on global state), then test two complementary properties: (1) deterministic per-move invariants (existing tiles follow slide_line and at most one previously empty cell receives 2 or 4), and (2) statistical bounds over 1,000 seeded spawns (asserting 50 <= fours <= 150 around the expected 100 fours so broken probabilities fail reliably without flaky runs).

Follow-up questions

Similar questions

More Asana interview questions

All 24 Asana questions →