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): ReturnTrueif and only if one edge isTABand the other isBLANKwith matchingshape(FLATedges never interlock with any edge).Piece(piece_id, edges): Store the 4 edges at orientation0in[TOP, RIGHT, BOTTOM, LEFT]order (raiseValueErroriflen(edges) != 4).rotate(turns=1)rotates clockwise by90 * turnsdegrees (negativeturnsrotate counterclockwise), andedge(side)returns whicheverEdgecurrently facesside.JigsawBoard:can_place(piece, row, col)returnsTrueiff(row, col)is in bounds and unoccupied,piece.piece_idis not already placed elsewhere on the board, every side facing outside the board boundary isFLAT, every side facing an interior neighbor cell is non-FLAT, and every side touching an already-placed neighbor satisfiesfitsagainst that neighbor's facing edge.place(piece, row, col)placespiecewhencan_placeholds and returns whether placement succeeded.remove(row, col)removes and returns the piece at(row, col)(orNoneif empty or out of bounds);piece_at(row, col)inspects without removing.is_complete()returnsTrueiff 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 index0(0marks an empty cell), fuse equal adjacent numbers at most once per turn starting from index0, pad trailing0s to keeplen(line)unchanged, and return(new_line, points_earned)wherepoints_earnedsums the values of newly created merged tiles.Game2048:- Expose
self.score(starting at0) andself.board(copied row-by-row fromboardwhen supplied; otherwise initialized to an emptysize x sizegrid followed by twospawn_tile()calls). Seed a dedicated RNG withseedso spawns are reproducible. move(direction)slides and merges every row or column towarddirection(raisingValueErrorifdirectionis invalid). If at least one cell changed, add the merged points toself.score, callspawn_tile()once, and returnTrue; otherwise change nothing and returnFalse.spawn_tile()places2(probability0.9) or4(probability0.1) on a uniformly chosen empty cell and returns(row, col), orNoneif no empty cell remains.is_game_over()returnsTrueiff no cell equals0and no two horizontally or vertically adjacent cells hold equal values.
- Expose
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 >= 1andcols >= 1forJigsawBoard;turnsinPiece.rotate(turns)may be any negative, zero, or positive integer.size >= 2forGame2048; empty cells contain0and occupied cells contain positive powers of2.- Passing an initial
boardtoGame2048must not mutate the caller's list when moves occur.
Step-by-step walkthrough
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:
- Define the input-size variables explicitly: Clarify what
n(andm, if present) measures — list length, character count, tree node count, or the magnitude of an integer. - Trace a tiny concrete input (
3–4items) and summarize the goal in one sentence: Never narrate code line by line ("setito0, then loop whilei < n..."). Trace[3, 1, 3], observe the output, and state the purpose ("ReturnsTrueiff the sequence contains a repeated value"). - Sum dependent loop iterations instead of blindly multiplying: Two independent
0..nloops multiply toO(n^2), whereas an inner loop bounded by the outer variable (for j in range(i)orwhile i < n: ... i *= 2) requires summing the work across rounds. - Spot hidden
O(n)costs inside single expressions: Watch forx 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. - Separate auxiliary space from input size: Count newly allocated hash sets, dictionaries, lists, slices, and the deepest call-stack frame depth of recursive calls.
- State cost assumptions clearly: Note
O(1)expected vsO(n)worst-case hashing, fixed-widthO(1)arithmetic, and best/average/worst cases when early exits exist.
- Define the input-size variables explicitly: Clarify what
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, returningTrueat the first repeat andFalsewhen all elements are distinct. - Time complexity: With
n = len(nums), the loop performs at mostnhash membership checks and insertions. UnderO(1)average hashing, runtime isO(n)expected (best caseO(1)whennums[0] == nums[1]; worst caseO(n^2)only under adversarial hash collisions). - Space complexity:
O(n)auxiliary space in the worst case when allnitems are unique and stored inseen.
Snippet B: Doubling outer loop — the classic
O(n)vsO(n log n)trapdef 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
2strictly belown(1 + 2 + 4 + ...). Whenn = 10,ivisits1, 2, 4, 8and returns15. - Time complexity: Multiplying "outer runs
log2(n)times" by "inner runs up tontimes" gives a looseO(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 < 2nBecause each round doubles the previous one, all earlier rounds combined total less than the single final round (
1 + 2 + 4 = 7 < 8). Since2^(k-1) < n, total iterations stay strictly below2n, giving tight runtimeO(n)(Theta(n)). - Space complexity:O(1)auxiliary space for two integer variablestotalandi.- Plain-English summary: Determines whether any value appears at least twice in
Part 2: Model Jigsaw edges and O(1) piece rotation
Now let's build
Edge,Piece, andJigsawBoard. Each piece has 4 sides (TOP = 0, RIGHT = 1, BOTTOM = 2, LEFT = 3clockwise) and rotates in 90-degree increments:Edge(kind, shape): An immutable value object (@dataclass(frozen=True)).kindisFLAT(straight border),TAB(outward knob), orBLANK(inward socket), andshapeidentifies the cut profile sofitsreturnsTrueiff one isTAB, the other isBLANK, and theirshapeintegers match.Piece(piece_id, edges): Keeps its 4 initial edges[E0, E1, E2, E3]fixed atrotation = 0, alongside an orientation counterself.rotationin{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)intoTOP (0)((0 - 1) % 4 = 3), oldTOP (0)intoRIGHT (1)((1 - 1) % 4 = 0), and in generalself.edges[(side - self.rotation) % 4]inO(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]Part 2: Validate placements, removals, and board completion
JigsawBoardstores arows x colsgrid plusself.position(piece_id -> (row, col)) forO(1)duplicate-piece checks.can_place(piece, row, col)checks four conditions:(row, col)lies inside the grid and is currentlyNone.piece.piece_idis not already on the board.- Every side facing outside the grid boundary is
FLAT, and every side facing another grid cell is notFLAT. - Every already-placed neighbor satisfies
my_edge.fits(neighbor.edge(opposite(side))).
Notice why
is_complete()re-checks_fits_hereon every cell instead of merely checkinglen(self.position) == rows * cols: becausePieceis mutable, rotating an already-placed piece in place would break joints without changinglen(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 TruePart 3: Solve 2048 for a single line without double-merging
Every direction in 2048 (
left,right,up,down) runs the exact same 1D rule alongsizelines. Let's writeslide_line(line)— sliding non-zero tiles toward index0— 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, pointsPart 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 columnindexordered 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_linealongcells, runslide_line(old_line), and writenew_lineback along those samecells: 1. Blocked-move guard: Only if at least one line changed (new_line != old_line) do we addgained_pointstoself.scoreand invokeself.spawn_tile(). 2. Deterministic spawning: Use a privateself.rng = random.Random(seed)to place2(0.9probability) or4(0.1probability) on a random empty cell. 3. Game-over check: Legal moves still exist iff any cell is0OR 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 TrueWalk through Examples 1 and 2 end to end
Walk-through of Example 1 (
1 x 2JigsawBoard): -left_piece([TOP=FLAT, RIGHT=TAB(5), BOTTOM=FLAT, LEFT=FLAT]) goes into(0, 0)cleanly because its three outer sides areFLATand its interiorRIGHTside isTAB(5). -right_piecestarts as[TOP=BLANK(5), RIGHT=FLAT, BOTTOM=FLAT, LEFT=FLAT]. At(0, 1),TOPfaces outside the board (BLANK(5) != FLAT) andLEFTfaces(0, 0)(FLATinside the board), socan_placereturnsFalse. - Callingright_piece.rotate(-1)setsself.rotation = 3: nowLEFT (3)readsedges[(3 - 3) % 4] = BLANK(5)(which interlocks withleft_piece'sTAB(5)!) andTOP,RIGHT,BOTTOMreadFLAT, soplace(right_piece, 0, 1)andis_complete()both returnTrue.Walk-through of Example 2 (
move("right")onGame2048):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 8Row
0proves whyslide_linenever chain-merges[8, 4, 4]into16, while row3merges two separate pairs of4s for+16. Totalscorerises to28, and one2or4spawns in an empty cell.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 1board: All four sides sit on the outer border, so only a piece with fourFLATedges fits. - Rotating an already-placed Jigsaw piece: Because callers hold references to
Pieceinstances, mutatingp.rotate()afterboard.place(p, r, c)breaks joints;is_complete()detects this by re-evaluating_fits_hereon every cell. - Negative and multi-turn rotations:
rotate(-1)androtate(5)wrap cleanly via(self.rotation + turns) % 4. - Placing the same
Piecetwice: Blocked inO(1)bypiece.piece_id in self.position. - 2048 single-merge traps:
[4, 0, 4, 4]produces[8, 4, 0, 0](+8points);[8, 4, 4, 0]produces[8, 8, 0, 0](+8points, never[16, 0, 0, 0]);[4, 4, 4, 4]produces[8, 8, 0, 0](+16points). - Blocked (no-op) 2048 swipe: When a move leaves every cell unchanged,
movereturnsFalse, adds0points, 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 ofO(n)on geometric series loops (1 + 2 + 4 + ... < 2n), or missing hiddenO(n)operations likex in list_obj. - Part 2 — Using
(side + self.rotation) % 4instead of(side - self.rotation) % 4: Addingrotationturns edges counterclockwise while claiming clockwise; verifyrotate(1)by checking that oldLEFT (3)moves toTOP (0). - Part 2 — Checking only top and left neighbors in
can_place: Interactive placement allows pieces in any order, so all4sides (plus border vs interiorFLATrules) must be checked. - Part 3 — Double-merging tiles in one turn: Stepping
i += 1or merging againstmerged_line[-1]turns[8, 4, 4, 0]into[16, 0, 0, 0]. - Part 3 — Scanning
"right"or"down"from index0instead 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 returnFalsebeforespawn_tile()whennot changed, and copy each row in__init__.
Alternative approaches
- 2048 via matrix transformations: Implement only
move_left(grid), then expressright,up, anddownvia row reversal and matrix transpose aroundmove_left. Very compact (O(n^2)), though it allocates several intermediate grids per move compared with_line_cells. - Signed-integer Jigsaw edges: Encode
FLATas0,TABof shapesas+s, andBLANKof shapesas-s, so two edges interlock iffe1 != 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 viaremoveon 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 hasO(1)valid candidates so the entire puzzle solves inO(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. Callingundo()pops that snapshot and restoresself.board,self.score, andself.rng.setstate(saved_state)— guaranteeing that replaying the same move reproduces the exact same spawned tile and cell inO(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
seedinto a privaterandom.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 followslide_lineand at most one previously empty cell receives2or4), and (2) statistical bounds over1,000seeded spawns (asserting50 <= fours <= 150around the expected100fours so broken probabilities fail reliably without flaky runs).
Follow-up questions
- How would you build an automated solver for JigsawBoard, and when does the search stay fast versus intractable?
- How can Game2048 support an undo() operation without letting players re-roll for luckier tile spawns?
- What is the cleanest strategy for unit-testing game mechanics that depend on random tile generation?
Similar questions
- Configurable 2048 Sliding-Tile Engine
- Layered ASCII Rectangle Canvas Engine
- Testable 2048 Grid Engine
- Architecting a Pluggable Animal-Chess Engine
- Heavy-Hitter IPv4 Addresses Under Tight Memory
- Asymmetric Cats and Rabbits Grid Engine
More Asana interview questions
- Layered ASCII Rectangle Canvas Engine Medium
- Architect a Scalable Microblogging Platform Medium
- Engineering Behavioral Prompts: Impact, Mentorship, Disagreement, and Clarity Medium Pro
- Select K Nearest Coordinates to the Origin Medium Pro
- Multi-Line Banner Glyph Renderer Medium Pro
- Asymmetric Cats and Rabbits Grid Engine Medium Pro
- Assemble a Rectangular Edge-Matching Tile Puzzle Medium Pro
- Two-Player Chess Engine and Legal Move Validator Medium Pro
- Cross-Team Collaboration: Delivering Engineering Projects Across Org Boundaries Medium Pro
- K Closest Numbers to a Target in a Sorted Array Medium Pro