Design Snake Game

MediumDesignsimulation

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Simulate the classic Snake game on a grid with height rows and width columns. The snake starts as a single cell at the top-left corner (0, 0) (row, column). You are given food, a list of [row, col] cells. Food appears **one piece at a time** in list order: the next piece only appears after the previous one is eaten. Each piece eaten adds 1 to the score and makes the snake one cell longer. - SnakeGame(width, height, food) starts a game. - move(direction) moves the head one cell "U", "D", "L", or "R" and returns the score after the move, or -1 if the game is over. A move works like this: if the new head cell is outside the grid, the game ends. If the new head cell holds the current food, the snake grows (its tail stays). Otherwise the tail cell is vacated first, so the head **may move into the cell the tail just left**. If the new head then lands on any other cell of the snake's body, the game ends. Once the game is over, every later move also returns -1. A food piece never appears on a cell occupied by the snake.

Examples

Input: ["SnakeGame","move","move","move","move","move","move"] [[4,2,[[1,1],[1,3]]],["D"],["R"],["R"],["R"],["U"],["R"]]
Output: [null,0,1,1,2,2,-1]
The snake eats at (1,1) and (1,3), reaching length 3. From (0,3), moving right leaves the 4-column grid.
Input: ["SnakeGame","move","move","move","move","move"] [[2,2,[[0,1],[1,1]]],["R"],["D"],["L"],["U"],["R"]]
Output: [null,1,2,2,2,2]
After eating twice the snake fills 3 of the 4 cells. It keeps circling because each move enters the cell its tail just vacated.

Constraints

  • `1 <= width, height <= 10^4`
  • `0 <= food.length <= 50`, and `food[i]` is inside the grid.
  • A food piece never appears on a cell occupied by the snake, and the first piece is not at `(0, 0)`.
  • `direction` is one of `"U"`, `"D"`, `"L"`, `"R"`; at most 10^4 calls to `move`.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More simulation problems