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 locked is True, if card_id is absent from the active board, or if card_id is already face up (either matched earlier or already flipped in the active turn).
    • Otherwise turn card_id face up.
    • When a first card is turned up, the turn waits for a partner (moves and locked do not change).
    • When a second distinct card is turned up, increment moves by 1 and compare their "value" fields:
      • Equal values: mark both cards permanently matched (matched = True, staying face_up = True) and keep locked = False.
      • Different values: immediately set locked = True and schedule both mismatched cards to flip face down 1000 ms from the current simulated time.
  • "advance" with [ms]:
    • Advance the simulated clock by ms milliseconds. If a mismatch delay is active and at least 1000 ms have elapsed since that mismatch occurred, flip the two unmatched cards face down, set locked = False, and clear the pending timer. Matched cards never flip back down.
  • "restart" with [new_cards] (or [] to reuse the current deck):
    • Replace the board with new_cards in the given order, with all cards face down and unmatched, clear any partial turn, set locked = False, and cancel any pending mismatch delay so an earlier round's timer cannot affect the new round. Cumulative moves carries over across restarts.

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 * k cards (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 at 1000 ms.

Step-by-step walkthrough

  1. 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):

    • cards is 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 by ms milliseconds.
      • 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 after advance(400) and flips face down after advance(600) (1000 ms total). - Locking: locked becomes True immediately on a mismatch and stays True until the 1000 ms delay expires (or the game restarts). Matched pairs never lock the board. - Moves: moves increments by 1 whenever a second distinct card is revealed (match or mismatch), and persists across restarts (Example 3 keeps moves: 1 after restart and reaches 2 on the next pair).

  2. 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:

    1. Third-card leak: Nothing blocks clicks during the 1000 ms wait, so clicking a third card adds it to revealed.
    2. 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.
    3. 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!
    
  3. 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 = True inside the same click step that reveals the second card blocks any third click immediately.
    • Storing hide_at_ms on the state object (and resetting hide_at_ms = None inside restart) means an old mismatch delay disappears the instant a new game loads.
  4. Code the board state and snapshot builder

    MemoryGame.__init__ initializes the two values that survive across restarts—self.moves and self.now_ms—and delegates board setup to _load_board(cards).

    snapshot() builds the dictionary expected by the judge. Notice that a card is face_up whenever it is permanently matched or temporarily in self.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(),
            }
    
  5. Code race-free clicks, clock advances, and restarts

    Now add the three transitions to MemoryGame:

    • click(card_id): First reject clicks when self.locked is True, when card_id is not on the current board, or when card_id is already face up (in self.matched_ids or in self.revealed_ids). Rejecting card_id in self.revealed_ids is crucial—without it, double-clicking card 'c2' would compare 'c2' against itself and score a fake match! When the second card is revealed, increment self.moves; if values match, move both IDs into self.matched_ids, otherwise set self.locked = True and self.hide_at_ms = self.now_ms + MISMATCH_DELAY_MS.
    • advance(ms): Add ms to self.now_ms. Once self.now_ms >= self.hide_at_ms, clear self.revealed_ids, unlock the board, and clear self.hide_at_ms = None.
    • restart(cards): Call self._load_board(cards), which wipes self.revealed_ids, unlocks the board, and sets self.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)
    
  6. Replay operations and trace Examples 2 and 3

    memory_card_game creates one MemoryGame and records game.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 snapshots
    

    Follow 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), restart loads ['r1', 'r2'] face down while keeping moves = 1 and clearing hide_at_ms = None, click 'r1' reveals 'r1', advance 1000 leaves 'r1' face up because the old timer was cancelled, and click 'r2' matches the pair (moves = 2, complete = True).

  7. Translate the state machine directly into React

    In a real React interview, this exact MemoryGame state machine becomes a useReducer reducer, with thin hooks connecting real browser timers, prop changes, and accessible markup:

    • useReducer avoids stale closures: Clicking a card dispatches { type: "click", id: card.id }, and React always passes the latest state into reducer.
    • Two layers of timer safety: A useEffect starts setTimeout only while state.locked is True and calls clearTimeout(timer) on cleanup (unmount, restart, or unlock). Tagging the action with gameId guarantees that even a late callback from an older round is ignored.
    • useRef detects prop deck changes cleanly: Comparing prevCardsRef.current !== cards dispatches "restart" only when the parent actually passes a new cards prop, 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 via aria-label (not color alone), and uses aria-disabled instead of HTML disabled so 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>
      );
    }
    
  8. 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): Each click and advance does O(1) average-time dictionary/set lookups (value_by_id, matched_ids) and scans revealed_ids of length at most 2. Each restart indexes n cards in O(n) time, and building the required board snapshot after each of the m operations visits all n cards in O(n) time. Since the output itself contains m * n card entries, O(m * n) is optimal.
  • Space — O(n) working state (O(m * n) including output): MemoryGame stores card_order, value_by_id, matched_ids, and revealed_ids, all bounded by O(n) cards; the returned snapshots list holds m snapshots of size n.

Edge cases

  • Double-clicking the same revealed card (click('c2'), click('c2')): The card_id in self.revealed_ids guard ignores the second click so 'c2' cannot pair with itself or increment moves.
  • 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 ms vs 1000 ms): self.now_ms >= self.hide_at_ms keeps the mismatched pair face up at 999 ms and flips it down at 1000 ms; a huge advance(5000) flips the mismatch once and leaves matched_ids untouched.
  • Restart during a mismatch or mid-turn: _load_board resets revealed_ids = [], locked = False, and hide_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 full 1000 ms window.
  • Move count across restarts: self.moves lives on the MemoryGame instance outside _load_board, preserving cumulative moves across restarts as shown in Example 3.

Common mistakes

  • Locking inside a useEffect instead of synchronously in the click transition: Effects run after React paints. If locked is set in an effect, a second fast click arriving before the effect runs still sees locked === false and reveals a third card.
  • Forgetting clearTimeout or ignoring game identity on restart: An uncancelled setTimeout from Round 1 fires during Round 2 and clears revealedIds. Always clean up the timer in useEffect and guard hideMismatch with a generation token (an incrementing gameId counter 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 use key={card.id}.
  • Using HTML disabled instead of aria-disabled: Setting disabled on a <button> the instant a user presses Enter/Space causes the browser to drop keyboard focus back to <body>. Setting aria-disabled (an ARIA attribute that announces a button as disabled to assistive technologies while keeping it focusable) preserves keyboard navigation while click ignores 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_number to every scheduled timer [fire_at, game_number] and ignore any timer whose game_number != current_game_number when it fires. This is a great reference model for randomized testing, and pairing it with clearTimeout in React gives defense in depth.
  • Parent-controlled key remount (<MemoryCardGame key={roundId} cards={cards} />): Changing a React component's key unmounts the old instance (running all effect cleanups and cancelling pending timers) and mounts a fresh state automatically. If moves must persist across restarts as in Example 3, lift moves up 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) -> nextState with no DOM imports and no real setTimeout calls—just like MemoryGame here. Unit tests can then feed hundreds of rapid click, advance, and restart sequences synchronously in milliseconds without waiting for real wall-clock delays. Only a couple of lightweight component tests using fake timers (vi.useFakeTimers() or jest.useFakeTimers()) are needed to verify that React's useEffect schedules and cleans up setTimeout.
  • Why does a single reducer model multi-field card transitions more safely here than separate useState hooks? useReducer shines whenever a single user action updates multiple interdependent fields at once and must uphold strict invariants. Revealing a second card simultaneously updates revealedIds, matchedIds, moves, and locked based on their latest values; keeping all of those updates inside one pure reducer(state, action) prevents impossible states like three revealed cards. In addition, React guarantees that dispatch has a stable identity across renders, so event handlers and setTimeout callbacks never capture stale state.
  • How should CSS flip transitions integrate with board state so visual animations never control turn progression? Keep reducer state 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 as data-face-up={isFaceUp}. Never rely on onTransitionEnd or onAnimationEnd events to unlock the board or advance game turns—browsers skip or cancel those events when users enable prefers-reduced-motion, switch tabs, or restart mid-flip. Share the MISMATCH_DELAY_MS constant 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 a schemaVersion number) to localStorage inside a useEffect whenever state changes, and hydrate it inside useReducer's lazy initializer after validating the JSON shape. Never persist raw timer IDs: if the user refreshes mid-mismatch (locked === true or two unmatched revealedIds), normalize the restored state by folding those two mismatched cards face down and setting locked: false so the board never reloads permanently stuck. Also check whether incoming cards props match the saved deck IDs, starting fresh if the parent supplied a new deck.

Follow-up questions

Similar questions

More Moment interview questions

All 1 Moment questions →