Concurrency-Safe Pair Matching Game
Medium · Software Engineering Fundamentals · Frontend Engineer · Technical Screen
Problem Statement
Model the state transitions and timing rules of a frontend pair-matching card game so that rapid clicks, delayed mismatch flips, and mid-game resets never corrupt the board.
An initial cards list describes the starting layout in display order. Each entry is a dictionary {"id": card_id, "value": match_value} where every "id" on the board is distinct and every "value" occurs on exactly two cards. At time 0 ms, every card is face down and unmatched, moves is 0, and locked is False.
Simulate a sequence of events given by operation_names[i] and operation_args[i]:
"click"with[card_id]:- Do nothing if
lockedisTrue, ifcard_idis absent from the active board, or ifcard_idis already face up (either matched earlier or already flipped in the active turn). - Otherwise turn
card_idface up. - When a first card is turned up, the turn waits for a partner (
movesandlockeddo not change). - When a second distinct card is turned up, increment
movesby1and compare their"value"fields:- Equal values: mark both cards permanently matched (
matched = True, stayingface_up = True) and keeplocked = False. - Different values: immediately set
locked = Trueand schedule both mismatched cards to flip face down1000ms from the current simulated time.
- Equal values: mark both cards permanently matched (
- Do nothing if
"advance"with[ms]:- Advance the simulated clock by
msmilliseconds. If a mismatch delay is active and at least1000ms have elapsed since that mismatch occurred, flip the two unmatched cards face down, setlocked = False, and clear the pending timer. Matched cards never flip back down.
- Advance the simulated clock by
"restart"with[new_cards](or[]to reuse the current deck):- Replace the board with
new_cardsin the given order, with all cards face down and unmatched, clear any partial turn, setlocked = False, and cancel any pending mismatch delay so an earlier round's timer cannot affect the new round. Cumulativemovescarries over across restarts.
- Replace the board with
After every operation, append a board snapshot dictionary:
{
"cards": [{"id": card_id, "face_up": bool, "matched": bool}, ...],
"moves": int,
"locked": bool,
"complete": bool, # True iff every card on the active board is matched
}
Return the list of snapshots (one per operation). Also be ready to discuss how this state machine maps cleanly onto accessible, race-free React state and keyboard-friendly controls without relying on color alone.
def memory_card_game(
cards: List[Dict[str, object]],
operation_names: List[str],
operation_args: List[List[object]],
) -> List[Dict[str, object]]:
Examples
Example 1
Input:
cards = [
{"id": "c1", "value": "sun"},
{"id": "c2", "value": "moon"},
{"id": "c3", "value": "moon"},
{"id": "c4", "value": "sun"},
]
operation_names = ["click", "click", "click", "click"]
operation_args = [["c2"], ["c2"], ["c3"], ["c1"]]
Output:
[
{"cards": [{"id": "c1", "face_up": False, "matched": False}, {"id": "c2", "face_up": True, "matched": False}, {"id": "c3", "face_up": False, "matched": False}, {"id": "c4", "face_up": False, "matched": False}], "moves": 0, "locked": False, "complete": False},
{"cards": [{"id": "c1", "face_up": False, "matched": False}, {"id": "c2", "face_up": True, "matched": False}, {"id": "c3", "face_up": False, "matched": False}, {"id": "c4", "face_up": False, "matched": False}], "moves": 0, "locked": False, "complete": False},
{"cards": [{"id": "c1", "face_up": False, "matched": False}, {"id": "c2", "face_up": True, "matched": True}, {"id": "c3", "face_up": True, "matched": True}, {"id": "c4", "face_up": False, "matched": False}], "moves": 1, "locked": False, "complete": False},
{"cards": [{"id": "c1", "face_up": True, "matched": False}, {"id": "c2", "face_up": True, "matched": True}, {"id": "c3", "face_up": True, "matched": True}, {"id": "c4", "face_up": False, "matched": False}], "moves": 1, "locked": False, "complete": False},
]
Walk-through: Clicking "c2" flips it face up (moves = 0). Clicking "c2" a second time is ignored because it is already revealed. Clicking "c3" pairs "moon" with "moon", marking both matched (moves = 1, locked = False). Clicking "c1" starts the next turn.
Example 2
Input:
cards = [
{"id": "c1", "value": "sun"},
{"id": "c2", "value": "moon"},
{"id": "c3", "value": "moon"},
{"id": "c4", "value": "sun"},
]
operation_names = ["click", "click", "click", "advance", "click", "advance"]
operation_args = [["c1"], ["c2"], ["c4"], [400], ["c3"], [600]]
Output:
Snapshots 2..5 all have "c1" and "c2" face up (unmatched), moves = 1, locked = True;
Snapshot 6 (at 400 + 600 = 1000 ms) flips all four cards face down with moves = 1, locked = False, complete = False.
Walk-through: Revealing "c1" ("sun") and "c2" ("moon") causes a mismatch (moves = 1, locked = True). Rapid clicks on "c4" at 0 ms and "c3" at 400 ms are rejected while locked. Advancing another 600 ms reaches 1000 ms total, flipping "c1" and "c2" face down and unlocking the board.
Example 3
Input:
cards = [
{"id": "p1", "value": 10},
{"id": "p2", "value": 20},
{"id": "p3", "value": 10},
{"id": "p4", "value": 20},
]
operation_names = ["click", "click", "restart", "click", "advance", "click"]
operation_args = [
["p1"],
["p2"],
[[{"id": "r1", "value": 99}, {"id": "r2", "value": 99}]],
["r1"],
[1000],
["r2"],
]
Output:
Snapshot 3 resets to [{"id": "r1", ...}, {"id": "r2", ...}] face down with moves = 1, locked = False;
Snapshot 5 keeps "r1" face up after advance(1000);
Snapshot 6 matches "r1" and "r2" with moves = 2, locked = False, complete = True.
Walk-through: "p1" and "p2" mismatch (moves = 1, timer due at 1000 ms). Calling restart loads the two-card deck ["r1", "r2"], unlocks input, keeps moves = 1, and cancels the old mismatch timer—so after "r1" is clicked, advance(1000) does not hide "r1". Clicking "r2" completes the new board (moves = 2, complete = True).
Constraints
- Every active deck contains
2 * kcards (k >= 1) with unique"id"values and exactly two cards per"value". 0 <= len(operation_names) == len(operation_args) <= 5,000"advance"arguments are non-negative integers in milliseconds; mismatch hide delay is fixed at1000ms.
Step-by-step walkthrough
Understand the game rules and the deterministic judge
To test rapid clicks, timers, and restarts reliably without a browser, the judge drives our game logic through
memory_card_game(cards, operation_names, operation_args):cardsis the initial deck: a list of{'id': ..., 'value': ...}dictionaries where IDs are unique and each value appears on a pair of cards.- Each operation is one of three events:
click [card_id]: flip an eligible face-down card face up.advance [ms]: move the simulated clock forward bymsmilliseconds.restart [new_cards]: load a new (possibly reshuffled) deck face down.
- After every operation, we append a board snapshot
{'cards': [{'id', 'face_up', 'matched'}, ...], 'moves', 'locked', 'complete'}in deck order.
Checking Examples 1–3 pins down every interaction detail: - Mismatch delay (
1000 ms): In Example 2, a mismatched pair stays face up afteradvance(400)and flips face down afteradvance(600)(1000 mstotal). - Locking:lockedbecomesTrueimmediately on a mismatch and staysTrueuntil the1000 msdelay expires (or the game restarts). Matched pairs never lock the board. - Moves:movesincrements by1whenever a second distinct card is revealed (match or mismatch), and persists across restarts (Example 3 keepsmoves: 1afterrestartand reaches2on the next pair).See why naive React handlers suffer from race conditions
A race condition is a bug where the outcome depends on the unpredictable timing of events such as rapid clicks, re-renders, and timers. Look at what goes wrong in a typical first React attempt:
function handleClick(id) { setRevealed([...revealed, id]); if (revealed.length === 1 && valueOf(revealed[0]) !== valueOf(id)) { setTimeout(() => setRevealed([]), 1000); } }Three timing races break this component under fast user input:
- Third-card leak: Nothing blocks clicks during the
1000 mswait, so clicking a third card adds it torevealed. - Stale closures: A stale closure happens when a function reads a variable captured from an older render that is already out of date. Two clicks arriving before React re-renders both see
revealed = [], so the second click overwrites the first card instead of completing a pair. - Zombie timeout across restarts: Look at what happens when a user restarts at
600 ms:
t = 0 ms Click 'p1', Click 'p2' (mismatch) -> starts setTimeout(..., 1000) due at t = 1000 ms t = 600 ms User clicks Restart! New deck ['r1', 'r2'] loads face down. t = 700 ms User clicks 'r1' in the NEW game -> 'r1' flips face up t = 1000 ms Old timer from Round 1 fires setRevealed([]) -> 'r1' suddenly vanishes!- Third-card leak: Nothing blocks clicks during the
Model the game as an explicit state machine with virtual time
We eliminate all three bugs by putting the entire board into one state machine (an object that transitions cleanly between well-defined states in response to events) and treating time as an explicit input rather than wall-clock
sleep:click 1st card ┌──────────┐ ───────────────────> ┌──────────┐ │ IDLE │ │ ONE_UP │ (1 card in revealed_ids, │ (0 up, │ <─────────────────── │ unlocked)│ clicks on same card ignored) │ unlocked)│ 2nd card MATCHES └────┬─────┘ └──────────┘ (add to matched_ids) │ 2nd card MISMATCHES ▲ ▼ │ now_ms >= hide_at_ms ┌─────────────────┐ └───────────────────────── │ LOCKED_MISMATCH │ (2 cards in revealed_ids, or restart(new_cards) │ locked = True │ hide_at_ms = now + 1000, └─────────────────┘ all clicks ignored!)- Every transition reads and mutates the single live state, making stale closures impossible.
- Setting
locked = Trueinside the sameclickstep that reveals the second card blocks any third click immediately. - Storing
hide_at_mson the state object (and resettinghide_at_ms = Noneinsiderestart) means an old mismatch delay disappears the instant a new game loads.
Code the board state and snapshot builder
MemoryGame.__init__initializes the two values that survive across restarts—self.movesandself.now_ms—and delegates board setup to_load_board(cards).snapshot()builds the dictionary expected by the judge. Notice that a card isface_upwhenever it is permanently matched or temporarily inself.revealed_ids.MISMATCH_DELAY_MS = 1000 class MemoryGame: """Pure state machine for the memory-card game using a virtual clock.""" def __init__(self, cards: List[Dict[str, object]]): # Completed pair comparisons; kept across restarts (see Example 3). self.moves = 0 # Simulated clock in milliseconds; moves forward only in advance(ms). self.now_ms = 0 self._load_board(cards) def _load_board(self, cards: List[Dict[str, object]]) -> None: """Initialize a fresh face-down board and cancel any pending mismatch.""" self.deck = list(cards) # card_order: card IDs in board display order, e.g. ['c1', 'c2', 'c3', 'c4']. self.card_order: List[object] = [] # value_by_id: maps each card ID to its match value, e.g. {'c1': 'sun'}. self.value_by_id: Dict[object, object] = {} for card in cards: card_id = card["id"] self.card_order.append(card_id) self.value_by_id[card_id] = card["value"] # revealed_ids: at most 2 unmatched card IDs face up in the current turn. self.revealed_ids: List[object] = [] # matched_ids: card IDs permanently matched so far. self.matched_ids: Set[object] = set() self.locked = False # hide_at_ms: timestamp when a mismatched pair flips down, or None. self.hide_at_ms: Optional[int] = None def is_complete(self) -> bool: return len(self.matched_ids) == len(self.card_order) def snapshot(self) -> Dict[str, object]: card_states = [] for card_id in self.card_order: is_matched = card_id in self.matched_ids is_face_up = is_matched or (card_id in self.revealed_ids) card_states.append({ "id": card_id, "face_up": is_face_up, "matched": is_matched, }) return { "cards": card_states, "moves": self.moves, "locked": self.locked, "complete": self.is_complete(), }Code race-free clicks, clock advances, and restarts
Now add the three transitions to
MemoryGame:click(card_id): First reject clicks whenself.lockedisTrue, whencard_idis not on the current board, or whencard_idis already face up (in self.matched_idsorin self.revealed_ids). Rejectingcard_id in self.revealed_idsis crucial—without it, double-clicking card'c2'would compare'c2'against itself and score a fake match! When the second card is revealed, incrementself.moves; if values match, move both IDs intoself.matched_ids, otherwise setself.locked = Trueandself.hide_at_ms = self.now_ms + MISMATCH_DELAY_MS.advance(ms): Addmstoself.now_ms. Onceself.now_ms >= self.hide_at_ms, clearself.revealed_ids, unlock the board, and clearself.hide_at_ms = None.restart(cards): Callself._load_board(cards), which wipesself.revealed_ids, unlocks the board, and setsself.hide_at_ms = None.
def click(self, card_id: object) -> None: # Ignore clicks while waiting for a mismatch to flip back down. if self.locked: return # Ignore unknown IDs (such as IDs from an old deck after a restart). if card_id not in self.value_by_id: return # Ignore cards already face up so double-clicking never matches a card with itself. if card_id in self.matched_ids or card_id in self.revealed_ids: return self.revealed_ids.append(card_id) if len(self.revealed_ids) < 2: return # Two distinct cards are now face up: count one completed comparison. self.moves += 1 first_id = self.revealed_ids[0] second_id = self.revealed_ids[1] if self.value_by_id[first_id] == self.value_by_id[second_id]: self.matched_ids.add(first_id) self.matched_ids.add(second_id) self.revealed_ids = [] else: # Lock synchronously so a rapid third click cannot enter this turn. self.locked = True self.hide_at_ms = self.now_ms + MISMATCH_DELAY_MS def advance(self, ms: int) -> None: self.now_ms += ms # Use >= so a mismatch at t=0 stays up at 999 ms and flips at 1000 ms. if self.hide_at_ms is not None and self.now_ms >= self.hide_at_ms: self.revealed_ids = [] self.locked = False self.hide_at_ms = None def restart(self, cards: List[Dict[str, object]]) -> None: # Reloading resets hide_at_ms to None, cancelling any pending mismatch timer. self._load_board(cards)Replay operations and trace Examples 2 and 3
memory_card_gamecreates oneMemoryGameand recordsgame.snapshot()after each operation:def memory_card_game(cards: List[Dict[str, object]], operation_names: List[str], operation_args: List[List[object]]) -> List[Dict[str, object]]: game = MemoryGame(cards) snapshots = [] for name, args in zip(operation_names, operation_args): if name == "click": game.click(args[0]) elif name == "advance": game.advance(args[0]) elif name == "restart": # Reuse the current deck if restart is called without a new card list. new_cards = args[0] if args else game.deck game.restart(new_cards) else: raise ValueError(f"unknown operation: {name}") snapshots.append(game.snapshot()) return snapshotsFollow how Example 2 (
c1, c4 = sun,c2, c3 = moon) handles rapid clicks during a mismatch:Operation now_ms revealed_ids locked hide_at_ms moves Notes click 'c1' 0 ['c1'] False None 0 1st card up click 'c2' 0 ['c1', 'c2'] True 1000 1 sun != moon -> lock! click 'c4' 0 ['c1', 'c2'] True 1000 1 Ignored (locked) advance 400 400 ['c1', 'c2'] True 1000 1 400 < 1000 -> still up click 'c3' 400 ['c1', 'c2'] True 1000 1 Ignored (locked) advance 600 1000 [] False None 1 1000 >= 1000 -> flip & unlock!And in Example 3,
'p1'and'p2'mismatch (moves = 1,hide_at_ms = 1000),restartloads['r1', 'r2']face down while keepingmoves = 1and clearinghide_at_ms = None,click 'r1'reveals'r1',advance 1000leaves'r1'face up because the old timer was cancelled, andclick 'r2'matches the pair (moves = 2,complete = True).Translate the state machine directly into React
In a real React interview, this exact
MemoryGamestate machine becomes auseReducerreducer, with thin hooks connecting real browser timers, prop changes, and accessible markup:useReduceravoids stale closures: Clicking a card dispatches{ type: "click", id: card.id }, and React always passes the lateststateintoreducer.- Two layers of timer safety: A
useEffectstartssetTimeoutonly whilestate.lockedisTrueand callsclearTimeout(timer)on cleanup (unmount, restart, or unlock). Tagging the action withgameIdguarantees that even a late callback from an older round is ignored. useRefdetects prop deck changes cleanly: ComparingprevCardsRef.current !== cardsdispatches"restart"only when the parent actually passes a newcardsprop, avoiding wasted mount renders.- Accessible buttons and stable keys: Using
<button type="button">inside<li key={card.id}>preserves DOM identity across reshuffles, gives Enter/Space keyboard support automatically, announces state viaaria-label(not color alone), and usesaria-disabledinstead of HTMLdisabledso flipping a card does not rip keyboard focus off the button.
import { useEffect, useReducer, useRef } from "react"; const MISMATCH_DELAY_MS = 1000; function createBoard(cards, moves, gameId) { return { cards, revealedIds: [], matchedIds: [], moves, locked: false, gameId }; } function reducer(state, action) { switch (action.type) { case "click": { const id = action.id; if (state.locked) return state; if (!state.cards.some((card) => card.id === id)) return state; if (state.matchedIds.includes(id) || state.revealedIds.includes(id)) return state; const revealedIds = [...state.revealedIds, id]; if (revealedIds.length < 2) return { ...state, revealedIds }; const [first, second] = revealedIds.map((rid) => state.cards.find((card) => card.id === rid) ); if (first.value === second.value) { return { ...state, revealedIds: [], matchedIds: [...state.matchedIds, first.id, second.id], moves: state.moves + 1, }; } return { ...state, revealedIds, locked: true, moves: state.moves + 1 }; } case "hideMismatch": if (action.gameId !== state.gameId || !state.locked) return state; return { ...state, revealedIds: [], locked: false }; case "restart": return createBoard(action.cards, state.moves, state.gameId + 1); default: return state; } } export function MemoryCardGame({ cards }) { const [state, dispatch] = useReducer(reducer, cards, (init) => createBoard(init, 0, 0)); const prevCardsRef = useRef(cards); useEffect(() => { if (prevCardsRef.current !== cards) { prevCardsRef.current = cards; dispatch({ type: "restart", cards }); } }, [cards]); useEffect(() => { if (!state.locked) return undefined; const currentGameId = state.gameId; const timerId = setTimeout(() => { dispatch({ type: "hideMismatch", gameId: currentGameId }); }, MISMATCH_DELAY_MS); return () => clearTimeout(timerId); }, [state.locked, state.gameId]); const complete = state.matchedIds.length === state.cards.length; return ( <section aria-label="Memory card game"> <ul> {state.cards.map((card, index) => { const isMatched = state.matchedIds.includes(card.id); const isFaceUp = isMatched || state.revealedIds.includes(card.id); const status = !isFaceUp ? "face down" : isMatched ? `${card.value}, matched` : `${card.value}, revealed`; return ( <li key={card.id}> <button type="button" aria-label={`Card ${index + 1}: ${status}`} aria-disabled={state.locked || isFaceUp} onClick={() => dispatch({ type: "click", id: card.id })} > {isFaceUp ? String(card.value) : "?"} </button> </li> ); })} </ul> <p role="status"> Moves: {state.moves}. {complete ? "All pairs matched!" : ""} </p> </section> ); }Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple # How long a mismatched pair stays face up before flipping back down. MISMATCH_DELAY_MS = 1000 class MemoryGame: """Pure state machine for the memory-card game using a virtual clock.""" def __init__(self, cards: List[Dict[str, object]]): # Completed pair comparisons; kept across restarts (see Example 3). self.moves = 0 # Simulated clock in milliseconds; moves forward only in advance(ms). self.now_ms = 0 self._load_board(cards) def _load_board(self, cards: List[Dict[str, object]]) -> None: """Initialize a fresh face-down board and cancel any pending mismatch.""" self.deck = list(cards) # card_order: card IDs in board display order, e.g. ['c1', 'c2', 'c3', 'c4']. self.card_order: List[object] = [] # value_by_id: maps each card ID to its match value, e.g. {'c1': 'sun'}. self.value_by_id: Dict[object, object] = {} for card in cards: card_id = card["id"] self.card_order.append(card_id) self.value_by_id[card_id] = card["value"] # revealed_ids: at most 2 unmatched card IDs face up in the current turn. self.revealed_ids: List[object] = [] # matched_ids: card IDs permanently matched so far. self.matched_ids: Set[object] = set() self.locked = False # hide_at_ms: timestamp when a mismatched pair flips down, or None. self.hide_at_ms: Optional[int] = None def click(self, card_id: object) -> None: # Ignore clicks while waiting for a mismatch to flip back down. if self.locked: return # Ignore unknown IDs (such as IDs from an old deck after a restart). if card_id not in self.value_by_id: return # Ignore cards already face up so double-clicking never matches a card with itself. if card_id in self.matched_ids or card_id in self.revealed_ids: return self.revealed_ids.append(card_id) if len(self.revealed_ids) < 2: return # Two distinct cards are now face up: count one completed comparison. self.moves += 1 first_id = self.revealed_ids[0] second_id = self.revealed_ids[1] if self.value_by_id[first_id] == self.value_by_id[second_id]: self.matched_ids.add(first_id) self.matched_ids.add(second_id) self.revealed_ids = [] else: # Lock synchronously so a rapid third click cannot enter this turn. self.locked = True self.hide_at_ms = self.now_ms + MISMATCH_DELAY_MS def advance(self, ms: int) -> None: self.now_ms += ms # Use >= so a mismatch at t=0 stays up at 999 ms and flips at 1000 ms. if self.hide_at_ms is not None and self.now_ms >= self.hide_at_ms: self.revealed_ids = [] self.locked = False self.hide_at_ms = None def restart(self, cards: List[Dict[str, object]]) -> None: # Reloading resets hide_at_ms to None, cancelling any pending mismatch timer. self._load_board(cards) def is_complete(self) -> bool: return len(self.matched_ids) == len(self.card_order) def snapshot(self) -> Dict[str, object]: card_states = [] for card_id in self.card_order: is_matched = card_id in self.matched_ids is_face_up = is_matched or (card_id in self.revealed_ids) card_states.append({ "id": card_id, "face_up": is_face_up, "matched": is_matched, }) return { "cards": card_states, "moves": self.moves, "locked": self.locked, "complete": self.is_complete(), } def memory_card_game(cards: List[Dict[str, object]], operation_names: List[str], operation_args: List[List[object]]) -> List[Dict[str, object]]: game = MemoryGame(cards) snapshots = [] for name, args in zip(operation_names, operation_args): if name == "click": game.click(args[0]) elif name == "advance": game.advance(args[0]) elif name == "restart": # Reuse the current deck if restart is called without a new card list. new_cards = args[0] if args else game.deck game.restart(new_cards) else: raise ValueError(f"unknown operation: {name}") snapshots.append(game.snapshot()) return snapshots✅ Submit now — all tests should pass.
Intuition & how it works
Think of a dealer running a tabletop memory-card game with a stopwatch. Players are never allowed to grab cards freely—every action goes through the dealer:
- While two mismatched cards lie face up for a 1-second peek, the dealer holds a hand over the table (locked = True) and ignores anyone reaching for a third card.
- If a player taps a card that is already face up, the dealer ignores it so a card can never match with itself.
- If players ask to reshuffle for a new round, the dealer sweeps the cards face down and resets the stopwatch (hide_at_ms = None), ensuring an old 1-second alarm never rings in the middle of the new round.
Why does the naive React approach fail? Scattering card state across separate useState hooks and firing raw setTimeout(() => setRevealed([]), 1000) callbacks inside onClick creates race conditions (bugs where correctness depends on the unpredictable timing of user clicks, React re-renders, and timers). Two rapid clicks before a re-render suffer from stale closures (handlers reading outdated variables captured from an earlier render), a third click slips in during the delay, and an uncancelled timeout from before a restart fires later and flips down cards in the new game.
Instead, we centralize every rule inside a single state machine (or React reducer, a pure function (state, action) -> nextState that computes the next state from the latest state) driven by a virtual clock (an integer timestamp now_ms advanced explicitly by advance(ms) so tests run instantaneously and deterministically).
Walk through 4 cards (c1 = sun, c2 = moon, c3 = moon, c4 = sun):
1. click('c1'): 'c1' enters revealed_ids = ['c1']; moves = 0, locked = False.
2. click('c2'): 'c2' enters revealed_ids = ['c1', 'c2']; moves becomes 1. Since 'sun' != 'moon', locked immediately flips to True and hide_at_ms is set to 0 + 1000 = 1000.
3. click('c4'): Ignored immediately because locked is True.
4. advance(1000): now_ms reaches 1000 >= hide_at_ms, so revealed_ids clears to [], locked becomes False, and hide_at_ms resets to None.
5. click('c2'), then click('c3'): 'moon' == 'moon', so both move into matched_ids = {'c2', 'c3'}, revealed_ids clears to [], moves = 2, and locked stays False.
Complexity
Let n be the maximum number of cards on the board and m be the number of operations.
- Time — O(m * n) total (
O(1)per transition,O(n)per restart and snapshot): EachclickandadvancedoesO(1)average-time dictionary/set lookups (value_by_id,matched_ids) and scansrevealed_idsof length at most2. Eachrestartindexesncards inO(n)time, and building the required boardsnapshotafter each of themoperations visits allncards inO(n)time. Since the output itself containsm * ncard entries,O(m * n)is optimal. - Space — O(n) working state (
O(m * n)including output):MemoryGamestorescard_order,value_by_id,matched_ids, andrevealed_ids, all bounded byO(n)cards; the returnedsnapshotslist holdsmsnapshots of sizen.
Edge cases
- Double-clicking the same revealed card (
click('c2'),click('c2')): Thecard_id in self.revealed_idsguard ignores the second click so'c2'cannot pair with itself or incrementmoves. - Clicks while locked: Ignored rather than buffered, so rapid clicks during a mismatch never trigger surprise flips when the timer expires.
- Clicks on matched cards or unknown IDs: Ignored safely—including clicks carrying card IDs from an old deck right after a
restart. - Exact millisecond boundary (
999 msvs1000 ms):self.now_ms >= self.hide_at_mskeeps the mismatched pair face up at999 msand flips it down at1000 ms; a hugeadvance(5000)flips the mismatch once and leavesmatched_idsuntouched. - Restart during a mismatch or mid-turn:
_load_boardresetsrevealed_ids = [],locked = False, andhide_at_ms = None, so neither a half-finished turn nor an old timer leaks into the new round, and any new mismatch gets its own full1000 mswindow. - Move count across restarts:
self.moveslives on theMemoryGameinstance outside_load_board, preserving cumulative moves across restarts as shown in Example 3.
Common mistakes
- Locking inside a
useEffectinstead of synchronously in the click transition: Effects run after React paints. Iflockedis set in an effect, a second fast click arriving before the effect runs still seeslocked === falseand reveals a third card. - Forgetting
clearTimeoutor ignoring game identity on restart: An uncancelledsetTimeoutfrom Round 1 fires during Round 2 and clearsrevealedIds. Always clean up the timer inuseEffectand guardhideMismatchwith a generation token (an incrementinggameIdcounter attached to each round so actions from older rounds are ignored). - Using array index as the React
key(key={index}): When the deck reshuffles,key={index}reuses the old DOM button at each grid slot, leaving keyboard focus and CSS flip transitions attached to the wrong card. Always usekey={card.id}. - Using HTML
disabledinstead ofaria-disabled: Settingdisabledon a<button>the instant a user presses Enter/Space causes the browser to drop keyboard focus back to<body>. Settingaria-disabled(an ARIA attribute that announces a button as disabled to assistive technologies while keeping it focusable) preserves keyboard navigation whileclickignores locked/face-up presses. - Communicating card state by color or icons alone: Screen-reader users need explicit text such as
aria-label="Card 2: moon, matched"and a<p role="status">live region for move/completion updates.
Alternative approaches
- Generation token without cancelling timers: Instead of cancelling timers on restart, attach the current
game_numberto every scheduled timer[fire_at, game_number]and ignore any timer whosegame_number != current_game_numberwhen it fires. This is a great reference model for randomized testing, and pairing it withclearTimeoutin React gives defense in depth. - Parent-controlled
keyremount (<MemoryCardGame key={roundId} cards={cards} />): Changing a React component'skeyunmounts the old instance (running all effect cleanups and cancelling pending timers) and mounts a fresh state automatically. Ifmovesmust persist across restarts as in Example 3, liftmovesup to the parent component.
Follow-up questions
- How can you structure the turn rules so unit tests run deterministically without mounting a UI component or waiting on real timers? Extract all rules into a pure state machine or reducer function
(state, action) -> nextStatewith no DOM imports and no realsetTimeoutcalls—just likeMemoryGamehere. Unit tests can then feed hundreds of rapidclick,advance, andrestartsequences synchronously in milliseconds without waiting for real wall-clock delays. Only a couple of lightweight component tests using fake timers (vi.useFakeTimers()orjest.useFakeTimers()) are needed to verify that React'suseEffectschedules and cleans upsetTimeout. - Why does a single reducer model multi-field card transitions more safely here than separate
useStatehooks?useReducershines whenever a single user action updates multiple interdependent fields at once and must uphold strict invariants. Revealing a second card simultaneously updatesrevealedIds,matchedIds,moves, andlockedbased on their latest values; keeping all of those updates inside one purereducer(state, action)prevents impossible states like three revealed cards. In addition, React guarantees thatdispatchhas a stable identity across renders, so event handlers andsetTimeoutcallbacks never capture stale state. - How should CSS flip transitions integrate with board state so visual animations never control turn progression? Keep
reducerstate as the single source of truth for logical card state (face_up,matched,locked), and drive visual 3D card flips purely through CSS transitions on an attribute such asdata-face-up={isFaceUp}. Never rely ononTransitionEndoronAnimationEndevents to unlock the board or advance game turns—browsers skip or cancel those events when users enableprefers-reduced-motion, switch tabs, or restart mid-flip. Share theMISMATCH_DELAY_MSconstant with CSS if you want the visual timing to coordinate, while keeping turn progression strictly in the reducer timer. - What state should you save to
localStorage—and how should you sanitize it on reload—to resume a session after a browser refresh? Serialize the pure board data (cards,matchedIds,revealedIds,moves, plus aschemaVersionnumber) tolocalStorageinside auseEffectwhenever state changes, and hydrate it insideuseReducer's lazy initializer after validating the JSON shape. Never persist raw timer IDs: if the user refreshes mid-mismatch (locked === trueor two unmatchedrevealedIds), normalize the restored state by folding those two mismatched cards face down and settinglocked: falseso the board never reloads permanently stuck. Also check whether incomingcardsprops match the saved deck IDs, starting fresh if the parent supplied a new deck.
Follow-up questions
- How can you structure the turn rules so unit tests run deterministically without mounting a UI component or waiting on real timers?
- Why does a single reducer model multi-field card transitions more safely here than separate `useState` hooks?
- How should CSS flip transitions integrate with board state so visual animations never control turn progression?
- What state should you save to `localStorage`—and how should you sanitize it on reload—to resume a session after a browser refresh?
Similar questions
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager
- Transactional Shopping Cart with Nested Scopes