15% off all plans & roadmaps Use code
See plansDesign Snake Game
- LeetCode 353
- Medium
- Design Patterns
- Design (General/Specific)
Updated
TL;DR: You simulate a snake on a grid and return the score after each move, or -1 once the game ends. The fast version stores the snake as a queue of cells and a hash set of occupied cells, so each move avoids scanning the board or the body.
Problem
You are designing a Snake Game on a 2D grid with width x height cells. The snake starts at (0, 0). Each move, it goes one cell in one of four directions: 'U' (up), 'D' (down), 'L' (left), or 'R' (right).
The game receives a list food, where food[i] = [ri, ci] gives the row and column of the i-th food item. Food appears on the board in the order given.
When the snake moves, its head enters the next cell. If that cell holds food, the snake eats it and grows by one. Otherwise the snake moves forward and its tail leaves the cell it occupied. The game ends if the snake moves out of bounds or runs into its own body.
Implement the following methods.
SnakeGame(int width, int height, int[][] food)sets up the game with the grid size and food positions.int move(String direction)moves the snake in the given direction. It returns the score, which is the number of food items eaten, or-1if the game is over because of a collision or an out-of-bounds move.
Example 1
Input: width = 1, height = 1, food = [], moves = ["R"] Output: [-1]
Constraints
1 <= width, height <= 10^41 <= food.length <= 50food[i].length == 20 <= ri < height0 <= ci < widthdirectionis one of'U','D','L','R'
Return the score after each move, or -1 if the game has ended.
Constraints that matter
- Width and height go up to 10^4, so the grid can hold 10^8 cells. Allocating a full board for each game rules out grid-based solutions.
- food.length is at most 50, so the snake grows at most 50 times and never has more than 51 cells. A scan over the body is short, which is why the brute force still runs quickly.
- Food appears in order, so each move compares the new head with one cell only, food[foodIndex]. You never search the food list.
- The tail must leave before the collision check on a non-eating move. This rule decides whether the head may enter the cell the tail last vacated.
Hints
Hint 1
This is a simulation problem.
Hint 2
This is the solution a beginner writes first.
Solution
Intuition
This is a simulation problem. The rules say what happens on each move, and your job is to keep only the state those rules need, then apply them one move at a time.
Picture a line of people waiting at a single door, where each new arrival joins the back and the person at the front leaves. The queue is the line, and the hash set is a whiteboard listing who is inside, so you check the board instead of asking everyone.
The snake behaves like a queue. Each move adds a new head at one end, and the tail leaves from the other end unless the snake eats. A queue gives you the tail in constant time, which is the operation that the movement rule needs most.
The board can hold 10^8 cells, but the snake occupies at most 51 of them. Track the snake and the next food item, not the board. A grid array would spend memory on cells the game never reads.
Collision is a membership question: is the new head on a body cell? A queue cannot answer that quickly, so pair it with a hash set that holds the same cells. The order rule still matters. When the snake does not eat, remove the tail from both structures before the collision check.
Worked example
Input: width = 1, height = 1, food = [], moves = ["R"] Output: [-1] Explanation: The board has one cell, at (0, 0), and the snake starts there. Moving right takes the head to column 1, which is outside a board of width 1. The game ends on the first move, so the answer is -1.
Approach 1: Brute force: list and linear scan
This is the solution a beginner writes first. Store the body as a list of (row, col) cells with the tail at index 0 and the head at the end. On each move, compute the new head, check the bounds, drop the tail if the snake does not eat, and scan the whole body for a collision. The result is correct, and it is the baseline for the next approach.
The weak spot is the scan. Every move checks the new head against every body cell, and removing index 0 from a Python list shifts the rest of the list. Under the constraints the body holds at most 51 cells, so the cost stays small, but it still grows with the snake length.
Steps
- Store the body as a list of cells, with the tail at index 0 and the head at the last index.
- On move, read the head and apply the direction. If the new cell is outside the grid, set the game-over flag and return -1.
- If the new cell is not food, remove the tail at index 0.
- Scan every body cell. If one matches the new cell, set the game-over flag and return -1.
- Append the new head. If the cell was food, advance the food index and add one to the score. Return the score.
Dry run
The example is one move to the right on a 1 by 1 board. The head starts at (0, 0), so the candidate cell is (0, 1), and column 1 is not less than width 1, so the bounds check fails. The game is over and the call returns -1. The tail removal and the body scan never run.
Complexity
| Time | O(L) per move |
|---|---|
| Space | O(L) |
Let L be the snake length, which equals 1 plus the number of food items eaten. Under the constraints L is at most 51. Each move does a bounds check, a removal at the front of the list that shifts up to L cells, and one loop over at most L cells, so the work is O(L). The list stores L cells, so the space is O(L), and the grid size never enters either bound.
PythonTested in our runner
from typing import List, Optional
class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
self.width = width
self.height = height
self.food = food
self.food_index = 0
self.score = 0
self.over = False
self.body = [(0, 0)] # index 0 is the tail, the last cell is the head
def move(self, direction: str) -> int:
if self.over:
return -1
r, c = self.body[-1]
if direction == 'U':
r -= 1
elif direction == 'D':
r += 1
elif direction == 'L':
c -= 1
else:
c += 1
if not (0 <= r < self.height and 0 <= c < self.width):
self.over = True
return -1
eats = self.food_index < len(self.food) and self.food[self.food_index] == [r, c]
if not eats:
self.body.pop(0) # shifts the list, fine for L <= 51
if (r, c) in self.body: # linear scan of the body
self.over = True
return -1
self.body.append((r, c))
if eats:
self.food_index += 1
self.score += 1
return self.score
The Design (General/Specific) infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Design (General/Specific)
Part of Design Patterns
Approach 2: Queue and hash setOptimalDesign (General/Specific)
What is slow in the brute force is the collision scan. Each move checks the new head against every body cell, even though the only question is whether one cell is occupied. The insight that fixes it is a hash set that mirrors the queue. Membership becomes one lookup, and the tail leaves both structures in constant time.
The queue still records the order of the body, so the tail is always the oldest cell. The order rule stays the same. On a move that does not eat, remove the tail from both structures before you check the new head. On a move that eats, the tail stays, so the head cannot enter it.
Why it is correct. The queue and the hash set always hold exactly the same cells, which are the current snake body. Each move updates both together, so a set lookup answers the collision question exactly. Removing the tail before the check is right, because the tail cell is vacated in the same move the head advances.
Steps
- Create a queue of cells holding the start cell. The front is the tail and the back is the head. Put the same cell in a hash set.
- On move, read the head from the back of the queue and apply the direction.
- If the new cell is outside the grid, set the game-over flag and return -1.
- If the cell is not food, remove the tail from the front of the queue and from the set.
- If the new cell is in the set, set the game-over flag and return -1. Otherwise push the cell to the back of the queue and add it to the set.
- If the cell was food, advance the food index and add one to the score. Return the score.
Dry run
| Step | What happens | Head | Queue and set | Result |
|---|---|---|---|---|
| 1 | Read the head and apply 'R' | (0, 0) | queue [(0, 0)], set {(0, 0)} | candidate cell (0, 1) |
| 2 | Bounds check: column 1 is not below width 1 | (0, 0) | unchanged | out of bounds |
| 3 | Set the game-over flag and return | (0, 0) | unchanged | return -1 |
The example has one move, so the table has three rows. Any later call returns -1 at once because of the flag. The food list is empty, so the food check never matches.
Complexity
| Time | O(1) average per move |
|---|---|
| Space | O(L) |
Each move does a fixed number of queue operations, one bounds check, and at most one set lookup, so the work per move is constant. Hash set lookups and inserts take expected O(1) time. The queue and set hold at most L cells, where L is the snake length and is at most 51 here, so the space is O(L). In Python, Java, C++ and C# the popped cells are freed, while JavaScript and Go keep popped slots in an array, so their memory grows with the number of moves.
PythonTested in our runner
from typing import List, Optional
from collections import deque
class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
self.width = width
self.height = height
self.food = food
self.food_index = 0
self.score = 0
self.over = False
self.body = deque([(0, 0)]) # left is the tail, right is the head
self.occupied = {(0, 0)}
def move(self, direction: str) -> int:
if self.over:
return -1
r, c = self.body[-1]
if direction == 'U':
r -= 1
elif direction == 'D':
r += 1
elif direction == 'L':
c -= 1
else:
c += 1
if not (0 <= r < self.height and 0 <= c < self.width):
self.over = True
return -1
eats = self.food_index < len(self.food) and self.food[self.food_index] == [r, c]
if not eats:
tail = self.body.popleft() # tail leaves before the collision check
self.occupied.remove(tail)
if (r, c) in self.occupied:
self.over = True
return -1
self.body.append((r, c))
self.occupied.add((r, c))
if eats:
self.food_index += 1
self.score += 1
return self.score
Common mistakes
if cell in bodychecked before the tail is removed on a non-eating move. This blocks the valid move into the cell the tail last left. Remove the tail first when the snake does not eat, then check the new head.- Removing the tail on a move that eats. The snake would shrink instead of grow. Pop the tail only when the new cell is not food.
- No game-over flag. After a collision the tail may already be removed, so later calls would move on and return scores. Store an
overflag and return -1 at the top ofmove. - Allocating a
height x widthgrid. With sizes up to 10^4 that is 10^8 cells. Track only the snake cells and the next food index. - Searching the whole food list for the new cell. Food appears in order, so the only food that matters is
food[foodIndex]. Advance the index only when the snake eats. - Swapping row and column. Food is given as
[row, col], andUdecreases the row whileLdecreases the column. Checkfood[foodIndex][0] == randfood[foodIndex][1] == c.
Edge cases
- A 1 by 1 board with the first move leaving the grid. The answer is -1, as in the example.
- Moving into the cell the tail last left on a move without food. The move is valid, and the score stays the same.
- Moving into the cell the tail last left on a move that eats food. The tail stays, so this is a collision and the answer is -1.
- Calling
moveagain after the game ended. Every later call returns -1, even if the direction would be legal on an empty board. - Eating the last food item. The food index moves past the end of the list, so the food check must test the length before indexing.
- The verified example passes an empty food list, which the constraints exclude. The code handles it, because the food check fails and the snake never eats.
Follow-ups interviewers ask
Follow-ups are part of Pro
The questions interviewers ask after you solve Design Snake Game, with how to answer them.
Unlock the follow-upsDesign Snake Game FAQ
What is the time complexity of Design Snake Game?
Each move takes O(1) average time with a queue and a hash set, and O(L) time with a list scan, where L is the snake length. Under the constraints L is at most 51. The bound counts work per move, so the board size does not affect it.
Why use a queue and hash set for Design Snake Game?
The queue returns the tail in constant time, which matches the first-in, first-out movement of the body. The set answers whether a cell is occupied with one lookup, which the queue alone cannot do quickly.
Can Design Snake Game be solved in O(1) extra space?
No, not in general. The snake's cells are the game state, so the queue and set must hold all of them, which takes O(L) space. Under the constraints L is at most 51, so the extra space is a small bounded amount in practice.
Why use deque instead of a list for the body in Python?
A list pop at index 0 shifts every remaining element, which costs O(L) per move. A deque removes from the left in O(1), so the tail removal stays constant time. The list version is correct, but the deque version matches the stated complexity.
Why does the tail get removed before the collision check?
On a move that does not eat, the tail moves out of its cell in the same turn the head moves in. Checking the new head first would flag a valid move into the vacated cell as a collision.
Asked at
See which companies ask this — Pro
Related problems
- LRU Cache · same technique: Design (General/Specific)
- Min Stack · same technique: Design (General/Specific)
- Time Based Key-Value Store · same technique: Design (General/Specific)
- Encode and Decode Strings · same technique: Design (General/Specific)
- Detect Squares · same technique: Design (General/Specific)
- Design Circular Queue · same technique: Design (General/Specific)
- Find Median from Data Stream · next harder, same pattern
- Implement Trie (Prefix Tree) · same pattern: Design Patterns
- Design Add and Search Words Data Structure · same pattern: Design Patterns
- Extra Characters in a String · same pattern: Design Patterns