Grid Snake Simulation and Hierarchy Validation

Medium · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

Implement snake_game_scores(width, height, moves, apples) to simulate a turn-by-turn Snake game on a bounded 2D board and return the player's score after each move.

The board has height rows numbered 0 through height - 1 from top to bottom and width columns numbered 0 through width - 1 from left to right. At the start of the game, the snake has length 1, occupies cell (0, 0), and has a score of 0.

You are given two sequences:

  • moves: direction commands where "U" steps to (row - 1, col), "D" steps to (row + 1, col), "L" steps to (row, col - 1), and "R" steps to (row, col + 1).
  • apples: food positions [row, col] that appear strictly one at a time in list order. Only apples[0] is present on the board at the beginning (when apples is non-empty); apples[k + 1] appears only right after apples[k] is eaten.

Process each command in moves according to these rules:

  1. Already crashed: Once the game ends on any turn, every subsequent command leaves the board unchanged and records -1.
  2. Wall check: Advance the head by one cell in the requested direction. If the new head position lies outside 0 <= row < height or 0 <= col < width, the game ends and -1 is recorded.
  3. Apple check & tail movement:
    • If the new head lands on the currently active apple, the snake eats it: the score increases by 1, the tail stays on its current cell (increasing the snake's length by 1), and the next entry in apples becomes active.
    • Otherwise, the tail vacates its cell during the same turn before self-collision is evaluated, so moving the head onto the cell just vacated by the tail is legal.
  4. Self-collision check: If the new head lands on any cell still occupied by the snake's body, the game ends and -1 is recorded; otherwise, the move succeeds and the current score is recorded.

(Companion interview topic: validating hierarchical employee reporting trees and detecting reporting cycles is explored in the follow-up questions.)

Examples

Example 1

Input: width = 3, height = 3, moves = ['D', 'R', 'R', 'U', 'L'], apples = [[1, 0], [0, 2]]

Output: [1, 1, 1, 2, 2]

Explanation: - 'D' moves the head to (1, 0), eating the first apple (score = 1, length 2) and revealing [0, 2]. - 'R' and 'R' move the head across (1, 1) to (1, 2) without eating (score stays 1). - 'U' moves the head to (0, 2), eating the second apple (score = 2, length 3). - 'L' moves the head safely to (0, 1) (score = 2).

Example 2

Input: width = 3, height = 2, moves = ['R', 'D', 'D', 'L'], apples = [[1, 1]]

Output: [0, 1, -1, -1]

Explanation: 'R' steps to (0, 1) (score = 0), and 'D' eats the apple at (1, 1) (score = 1). The second 'D' attempts to enter row 2 on a 2-row board, hitting the bottom wall (-1), so the trailing 'L' also reports -1.

Example 3

Input: width = 3, height = 2, moves = ['D', 'R', 'U', 'L', 'D'], apples = [[1, 0], [1, 1], [0, 1]]

Output: [1, 2, 3, 3, 3]

Explanation: The first three moves ('D', 'R', 'U') eat all three apples in order, growing the snake to length 4 from head (0, 1) through (1, 1) and (1, 0) to tail (0, 0). On 'L', the snake is not eating, so tail (0, 0) vacates first and head (0, 1) legally enters (0, 0). Likewise, 'D' vacates (1, 0) and steps into (1, 0), keeping score = 3.

Constraints

  • 1 <= width, height <= 10^5
  • 0 <= len(moves) <= 10^5
  • moves[i] is "U", "D", "L", or "R".
  • 0 <= len(apples) <= 10^5
  • Every [row, col] in apples lies inside [0, height - 1] x [0, width - 1] and is unoccupied at the moment it becomes active.

Step-by-step walkthrough

  1. Clarify the exact game rules

    snake_game_scores(width, height, moves, apples) simulates a sequence of movement keys and returns the score after every move:

    • Grid coordinates: the board has height rows (0 .. height - 1, top to bottom) and width columns (0 .. width - 1, left to right). Apples are given as [row, col].
    • Starting state: the snake starts at length 1 on (0, 0) with score 0.
    • One active apple at a time: only apples[0] is on the board initially. Only after apples[k] is eaten does apples[k + 1] appear, increasing both the score and the snake's length by 1.
    • Simultaneous movement: on a non-eating move, the tail vacates its cell in the same instant the head advances, so stepping onto the old tail cell is legal.
    • Game over: hitting a wall or another body segment ends the game immediately, recording -1 for that move and every move after it.
    Grid layout (width = 4 columns, height = 3 rows):
           col 0   col 1   col 2   col 3
    row 0  (0,0)   (0,1)   (0,2)   (0,3)      U: (-1,  0)
    row 1  (1,0)   (1,1)   (1,2)   (1,3)      D: (+1,  0)
    row 2  (2,0)   (2,1)   (2,2)   (2,3)      L: ( 0, -1)   R: ( 0, +1)
    
  2. Brute force with a plain list and why it slows down

    A straightforward prototype stores the snake's segments in a Python list body = [(0, 0)] with the head at index 0. On each move, it builds new_body = [next_head] + body (when eating) or new_body = [next_head] + body[:-1] (when not eating) and checks len(set(new_body)) == len(new_body) for self-collisions.

    That directly models the rules (and serves as our randomized test oracle), but slicing body[:-1], concatenating lists, and converting new_body to a set all copy every segment of the snake on every single move. If the snake eats L apples over m moves, each move takes O(L) work—up to O(m^2) total, or roughly 5 * 10^9 operations for 100,000 moves.

  3. Key insight: pair a deque with a hash set

    Notice that even a 100,000-cell snake only ever changes at its two ends: one cell is added at the head, and (when not eating) one cell is removed from the tail.

    We combine two data structures that stay synchronized on the exact same cells:

    • A deque (collections.deque, a double-ended queue that adds or removes elements at either end in O(1) time) maintains segment order from head (body[0]) to tail (body[-1]).
    • A hash set (occupied) stores those same (row, col) tuples so (next_row, next_col) in occupied checks self-collisions in O(1) average time.

    The exact order of operations inside each move is critical:

    Normal move (not eating):
      Before:  tail [T] --- [B] --- [H] head
      Step A:  pop tail [T] from `body` and `occupied` FIRST  --> cell T is now free!
      Step B:  check if new head is in `occupied`             --> stepping onto T is allowed!
      Step C:  push new head onto front of `body` and `occupied`
    
    Eating move:
      Before:  tail [T] --- [B] --- [H] head   (apple at A)
      Step A:  keep tail [T] in place (snake grows by 1)
      Step B:  push A onto front of `body` and `occupied`, increment score and apple_idx
    
  4. Initialize the game state

    Let's set up the direction lookup table and initialize the snake at (0, 0) with apple_idx = 0 pointing to the first apple in apples.

    from collections import deque
    
    # Map each movement key to its (row_delta, col_delta) step on the 2D grid.
    DIRECTIONS: Dict[str, Tuple[int, int]] = {
        "U": (-1, 0),
        "D": (1, 0),
        "L": (0, -1),
        "R": (0, 1),
    }
    
    # body: deque of (row, col) cells ordered from head at body[0] to tail at body[-1].
    body = deque([(0, 0)])
    # occupied: set of the exact same (row, col) cells in body for O(1) collision checks.
    occupied: Set[Tuple[int, int]] = {(0, 0)}
    
    # apple_idx: index into `apples` for the single apple currently visible on the board.
    apple_idx = 0
    score = 0
    game_over = False
    scores: List[int] = []
    
  5. Simulate each move in exact tick order

    Now process moves one key at a time:

    1. If game_over is already True, append -1 and skip the rest of the loop.
    2. Compute (next_row, next_col) and verify 0 <= next_row < height and 0 <= next_col < width.
    3. Check whether (next_row, next_col) matches apples[apple_idx].
    4. If not eats_apple, pop old_tail from both body and occupied before the collision test.
    5. Check (next_row, next_col) in occupied; if present, mark game_over = True and append -1.
    6. Otherwise add (next_row, next_col) to the front of body and to occupied, advance score and apple_idx when eating, and record score.
        for move in moves:
            # Phase 1: Once the snake has crashed, every subsequent move reports -1.
            if game_over:
                scores.append(-1)
                continue
    
            # Phase 2: Compute the next head position and check wall boundaries.
            # Note: `height` bounds row indices [0..height-1]; `width` bounds column indices [0..width-1].
            dr, dc = DIRECTIONS[move]
            head_row, head_col = body[0]
            next_row = head_row + dr
            next_col = head_col + dc
    
            if next_row < 0 or next_row >= height or next_col < 0 or next_col >= width:
                game_over = True
                scores.append(-1)
                continue
    
            # Phase 3: Check whether the new head lands on the currently active apple.
            eats_apple = (
                apple_idx < len(apples)
                and apples[apple_idx][0] == next_row
                and apples[apple_idx][1] == next_col
            )
    
            # Phase 4: If NOT eating, advance the tail BEFORE checking self-collision.
            # Because the tail vacates its cell in the same tick, the head may legally enter it.
            if not eats_apple:
                old_tail = body.pop()
                occupied.remove(old_tail)
    
            # Phase 5: Any remaining overlap with `occupied` is a fatal self-collision.
            if (next_row, next_col) in occupied:
                game_over = True
                scores.append(-1)
                continue
    
            # Phase 6: Commit the new head and update score / active apple if eaten.
            body.appendleft((next_row, next_col))
            occupied.add((next_row, next_col))
            if eats_apple:
                score += 1
                apple_idx += 1
            scores.append(score)
    
  6. Trace Example 3 (stepping onto the vacated tail)

    Let's trace width = 3, height = 2, moves = ['D', 'R', 'U', 'L', 'D'], apples = [[1, 0], [1, 1], [0, 1]]:

    Start:   body = [(0,0)]                        score = 0, active apple = [1,0]
    
    Move 'D' -> next (1,0) == [1,0] (eats!):
             body = [(1,0), (0,0)]                 score = 1, active apple = [1,1]
    
    Move 'R' -> next (1,1) == [1,1] (eats!):
             body = [(1,1), (1,0), (0,0)]          score = 2, active apple = [0,1]
    
    Move 'U' -> next (0,1) == [0,1] (eats!):
             body = [(0,1), (1,1), (1,0), (0,0)]   score = 3, active apple = none left
             Head is now at (0,1) and tail is at (0,0).
    
    Move 'L' -> next (0,0), eats_apple = False:
             1. Pop old_tail (0,0) from body and occupied -> (0,0) is now FREE.
             2. Is (0,0) in occupied? False!
             3. Push (0,0) as new head -> body = [(0,0), (0,1), (1,1), (1,0)], score = 3.
    
    Move 'D' -> next (1,0), eats_apple = False:
             1. Pop old_tail (1,0) from body and occupied -> (1,0) is now FREE.
             2. Is (1,0) in occupied? False!
             3. Push (1,0) as new head -> body = [(1,0), (0,0), (0,1), (1,1)], score = 3.
    

    Output: [1, 2, 3, 3, 3]. If we had checked (next_row, next_col) in occupied before popping the tail, move 'L' would have falsely returned -1.

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    from collections import deque
    
    # Map each movement key to its (row_delta, col_delta) step on the 2D grid.
    DIRECTIONS: Dict[str, Tuple[int, int]] = {
        "U": (-1, 0),
        "D": (1, 0),
        "L": (0, -1),
        "R": (0, 1),
    }
    
    
    def snake_game_scores(width: int, height: int, moves: List[str], apples: List[List[int]]) -> List[int]:
        # body: deque of (row, col) cells ordered from head at body[0] to tail at body[-1].
        body = deque([(0, 0)])
        # occupied: set of the exact same (row, col) cells in body for O(1) collision checks.
        occupied: Set[Tuple[int, int]] = {(0, 0)}
    
        # apple_idx: index into `apples` for the single apple currently visible on the board.
        apple_idx = 0
        score = 0
        game_over = False
        scores: List[int] = []
    
        for move in moves:
            # Phase 1: Once the snake has crashed, every subsequent move reports -1.
            if game_over:
                scores.append(-1)
                continue
    
            # Phase 2: Compute the next head position and check wall boundaries.
            # Note: `height` bounds row indices [0..height-1]; `width` bounds column indices [0..width-1].
            dr, dc = DIRECTIONS[move]
            head_row, head_col = body[0]
            next_row = head_row + dr
            next_col = head_col + dc
    
            if next_row < 0 or next_row >= height or next_col < 0 or next_col >= width:
                game_over = True
                scores.append(-1)
                continue
    
            # Phase 3: Check whether the new head lands on the currently active apple.
            eats_apple = (
                apple_idx < len(apples)
                and apples[apple_idx][0] == next_row
                and apples[apple_idx][1] == next_col
            )
    
            # Phase 4: If NOT eating, advance the tail BEFORE checking self-collision.
            # Because the tail vacates its cell in the same tick, the head may legally enter it.
            if not eats_apple:
                old_tail = body.pop()
                occupied.remove(old_tail)
    
            # Phase 5: Any remaining overlap with `occupied` is a fatal self-collision.
            if (next_row, next_col) in occupied:
                game_over = True
                scores.append(-1)
                continue
    
            # Phase 6: Commit the new head and update score / active apple if eaten.
            body.appendleft((next_row, next_col))
            occupied.add((next_row, next_col))
            if eats_apple:
                score += 1
                apple_idx += 1
            scores.append(score)
    
        return scores
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture a toy train moving across floor tiles: on an ordinary move, you snap one new engine car onto the tile ahead and lift the caboose off the back tile at the exact same moment, whereas whenever the engine picks up an apple, you leave the caboose where it is so the train grows one car longer.

Keeping the snake in a plain Python list and rebuilding [new_head] + body[:-1] or scanning the list for duplicates touches every segment of the snake on every move, slowing long games down to O(m^2) work. Worse yet, checking whether the head hits the body before lifting the caboose treats the departing tail tile as blocked and wrongly kills a snake chasing its own tail. Pairing a deque (a double-ended queue that adds to the front and removes from the back in O(1) time) with a hash set (an unordered collection supporting O(1) average membership tests) lets us update just the two ends of the snake and test collisions in constant time.

Walk through Example 3 on a 3 x 2 board with apples [1, 0], [1, 1], [0, 1] and moves ['D', 'R', 'U', 'L', 'D']: 1. Start with body = [(0, 0)] and score = 0. 2. 'D', 'R', and 'U' each land on the active apple in turn, keeping the tail in place so body grows to [(0, 1), (1, 1), (1, 0), (0, 0)] and scores records 1, 2, 3. 3. On 'L' (and similarly 'D'), the new head (0, 0) has no apple, so we first pop tail (0, 0) from body and occupied, verify (0, 0) is no longer in occupied, push (0, 0) to the front, and record 3.

Complexity

Let m be len(moves) and L be the maximum length reached by the snake (L <= 1 + len(apples) and L <= width * height).

  • Time: O(m) average time. We iterate through the m moves once; each live move performs O(1) arithmetic, at most one deque.pop() and deque.appendleft(), and O(1) average-time hash-set remove, in, and add operations, while moves after game_over simply append -1.
  • Space: O(L + m) total space, because body and occupied each store at most L coordinate tuples at a time, and the returned scores list stores m integers.

Edge cases

  • Empty moves list: the loop does not execute and returns [].
  • 1 x 1 grid: any first move crosses a wall boundary (< 0 or >= 1), returning [-1, -1, ...].
  • Asymmetric width vs. height: height bounds row (0 .. height - 1) and width bounds col (0 .. width - 1); swapping them breaks rectangular boards like width = 3, height = 2.
  • Chasing or reversing onto the tail: legal whenever not eats_apple (including a length-2 snake reversing back onto its second cell, or a snake filling all width * height cells).
  • Walking over a future apple early: only apples[apple_idx] is active; stepping on apples[apple_idx + 1] beforehand is a normal non-eating move.
  • Moves after crashing: once game_over becomes True, all remaining moves return -1 even if their direction would have been in-bounds.

Common mistakes

  • Testing (next_row, next_col) in occupied before popping the tail: falsely flags a collision whenever the snake moves into the cell its tail is simultaneously leaving (such as move 4 of Example 3).
  • Popping the tail on an eating move: keeps the snake at length 1 forever so self-collisions never happen.
  • Using in body on a deque without a companion set: tuple in deque performs a linear O(L) scan, turning a 100,000-move game into billions of comparisons.
  • Updating body while forgetting to update occupied: causes phantom collisions on long-ago cells or misses real collisions on recent cells.
  • Confusing [x, y] with [row, col] for apples: apples[i] is [row, col]; treating apples[0] = [1, 0] as column 1, row 0 misses the first apple in Example 1.

Follow-up questions

  • Suppose a companion task asks you to validate an organization chart where each employee record lists direct reports—how would you check business rules across all descendants and detect reporting cycles? Model the org chart as a directed graph (manager_id -> direct report_ids) and traverse it with depth-first search (DFS) (following each reporting chain as deep as possible before backing up). Track three states per employee: unvisited, "visiting" (currently on the active recursion stack, meaning an ancestor of the employee we are inspecting right now), and "done" (fully validated along with all descendants). Encountering a "visiting" node proves an employee indirectly reports back to themselves (a cycle), whereas encountering a "done" node simply skips redundant work in O(V + E) time across V employees and E reporting links:
def validate_employees(employees, check_rules):
    """employees: dict[emp_id, dict] with 'reports': list[emp_id].
    Returns (invalid_ids, missing_report_ids, has_cycle).
    """
    state = {}  # emp_id -> "visiting" (on active chain) or "done"
    invalid_ids = []
    missing_report_ids = []
    has_cycle = False

    def dfs(emp_id):
        nonlocal has_cycle
        if emp_id not in employees:
            missing_report_ids.append(emp_id)
            return
        if state.get(emp_id) == "done":
            return
        if state.get(emp_id) == "visiting":
            has_cycle = True
            return

        state[emp_id] = "visiting"
        if not check_rules(employees[emp_id]):
            invalid_ids.append(emp_id)
        for report_id in employees[emp_id].get("reports", []):
            dfs(report_id)
        state[emp_id] = "done"

    # Start from every employee so isolated cycles with no top-level root are still caught.
    for emp_id in employees:
        dfs(emp_id)
    return invalid_ids, missing_report_ids, has_cycle
  • How would you adapt this step-by-step simulator into a real-time interactive game driven by asynchronous keyboard events? Decouple keyboard events from simulation ticks: key-press handlers push requested directions into a small bounded input queue, while a fixed-interval game timer (say every 100 ms) pops one direction per tick (defaulting to the snake's current heading when the queue is empty) and runs our exact single-move update. Filter out opposite-direction inputs (such as 'L' while heading 'R' when len(body) >= 2) so a fast double-tap cannot make the head reverse directly into its neck.
  • If apples had to spawn on a uniformly random unoccupied cell instead of a preset list, how could you pick each spawn cell in O(1) time even when the snake covers almost the entire board? Random rejection sampling (pick random (r, c) until not in occupied) slows down drastically when 99% of cells are full. Instead, maintain a list free_cells of unoccupied (r, c) tuples alongside a dictionary pos_in_free mapping each free cell to its index in free_cells: removing an occupied cell swaps it with free_cells[-1] and pops in O(1), freeing a vacated tail cell appends in O(1), and random.choice(free_cells) picks a guaranteed empty cell in O(1) time.

Follow-up questions

Similar questions

More Amplitude interview questions

All 2 Amplitude questions →