KatInterview

353. Design Snake Game

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem requires us to design and implement a SnakeGame class. This involves managing the state of a snake on a 2D grid, including its position, length, and movement. The core challenges are:

Solution

Design Snake Game in Python

import collections

class SnakeGame:

    def __init__(self, width: int, height: int, food: list[list[int]]):
        """
        Initialize your data structure here.
        @param width - screen width
        @param height - screen height 
        @param food - a list of food positions
        E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].
        """
        self.width = width
        self.height = height
        self.food = food
        self.food_index = 0
        self.score = 0
        self.game_over = False

        # Snake body as a deque of (row, col) tuples
        self.snake_body = collections.deque([(0, 0)])
        # Set of snake body parts for O(1) collision checks
        self.snake_set = {(0, 0)}

        # Mapping directions to coordinate changes
        self.directions = {'U': (-1, 0), 'D': (1, 0), 'L': (0, -1), 'R': (0, 1)}

    def move(self, direction: str) -> int:
        """
        Moves the snake.
        @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down 
        @return The game's score after the move. Return -1 if game over.
        Game over when snake crosses the screen boundary or bites its body.
        """
        if self.game_over:
            return -1

        # Get current head position
        current_head = self.snake_body[0]
        dr, dc = self.directions[direction]
        next_head = (current_head[0] + dr, current_head[1] + dc)

        # Check for wall collision
        if not (0 <= next_head[0] < self.height and 0 <= next_head[1] < self.width):
            self.game_over = True
            return -1

        # Check if the snake eats food
        eats_food = (self.food_index < len(self.food) and 
                     next_head[0] == self.food[self.food_index][0] and
                     next_head[1] == self.food[self.food_index][1])

        # If the snake doesn't eat, the tail moves. We must remove the tail from the set
        # *before* checking for self-collision with the new head.
        if not eats_food:
            tail = self.snake_body.pop()
            self.snake_set.remove(tail)
        
        # Check for self-collision
        if next_head in self.snake_set:
            self.game_over = True
            return -1

        # Add the new head
        self.snake_body.appendleft(next_head)
        self.snake_set.add(next_head)

        if eats_food:
            self.score += 1
            self.food_index += 1
        
        return self.score

Design Snake Game in Java

class SnakeGame {
    private int width, height, score, foodIndex;
    private int[][] food;
    private Deque<int[]> snakeBody; // Stores snake's body coordinates {row, col}
    private Set<Integer> snakeSet; // Stores snake's body for O(1) collision checks
    private boolean gameOver;

    /** Initialize your data structure here.
        @param width - screen width
        @param height - screen height 
        @param food - a list of food positions
        E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. */
    public SnakeGame(int width, int height, int[][] food) {
        this.width = width;
        this.height = height;
        this.food = food;
        this.score = 0;
        this.foodIndex = 0;
        this.gameOver = false;
        
        // Use a Deque to represent the snake's body
        this.snakeBody = new LinkedList<>();
        this.snakeBody.addFirst(new int[]{0, 0});

        // Use a Set for quick collision checks
        this.snakeSet = new HashSet<>();
        this.snakeSet.add(0 * width + 0); // Encode (0,0)
    }
    
    /** Moves the snake.
        @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down 
        @return The game's score after the move. Return -1 if game over.
        Game over when snake crosses the screen boundary or bites its body. */
    public int move(String direction) {
        if (gameOver) {
            return -1;
        }

        // Get current head position
        int[] head = snakeBody.peekFirst();
        int nextRow = head[0];
        int nextCol = head[1];

        // Calculate next head position
        switch (direction) {
            case "U": nextRow--; break;
            case "D": nextRow++; break;
            case "L": nextCol--; break;
            case "R": nextCol++; break;
        }

        // Check for wall collision
        if (nextRow < 0 || nextRow >= height || nextCol < 0 || nextCol >= width) {
            gameOver = true;
            return -1;
        }

        // Check if snake eats food
        boolean eatsFood = (foodIndex < food.length && 
                            nextRow == food[foodIndex][0] && 
                            nextCol == food[foodIndex][1]);

        // If snake doesn't eat food, its tail moves forward.
        // We remove the tail from our records before checking for self-collision.
        if (!eatsFood) {
            int[] tail = snakeBody.pollLast();
            snakeSet.remove(tail[0] * width + tail[1]);
        }

        // Check for self-collision
        int newHeadPos = nextRow * width + nextCol;
        if (snakeSet.contains(newHeadPos)) {
            gameOver = true;
            return -1;
        }

        // Add new head
        snakeBody.addFirst(new int[]{nextRow, nextCol});
        snakeSet.add(newHeadPos);

        // If food was eaten, update score and food index
        if (eatsFood) {
            score++;
            foodIndex++;
        }

        return score;
    }
}

Design Snake Game in C++

class SnakeGame {
private:
    int width, height, score, foodIndex;
    vector<vector<int>> food;
    deque<pair<int, int>> snakeBody; // Stores snake's body coordinates (row, col)
    unordered_set<int> snakeSet; // Stores snake's body for O(1) collision checks
    bool gameOver;

    // Encodes a (row, col) pair into a single integer
    int encode(int r, int c) {
        return r * width + c;
    }

public:
    SnakeGame(int width, int height, vector<vector<int>>& food) {
        this->width = width;
        this->height = height;
        this->food = food;
        this->score = 0;
        this->foodIndex = 0;
        this->gameOver = false;

        // Snake starts at (0, 0)
        snakeBody.push_front({0, 0});
        snakeSet.insert(encode(0, 0));
    }
    
    int move(string direction) {
        if (gameOver) {
            return -1;
        }

        // Get current head position
        pair<int, int> head = snakeBody.front();
        int nextRow = head.first;
        int nextCol = head.second;

        // Calculate next head position
        if (direction == "U") nextRow--;
        else if (direction == "D") nextRow++;
        else if (direction == "L") nextCol--;
        else if (direction == "R") nextCol++;

        // Check for wall collision
        if (nextRow < 0 || nextRow >= height || nextCol < 0 || nextCol >= width) {
            gameOver = true;
            return -1;
        }

        // Check if snake eats food
        bool eatsFood = (foodIndex < food.size() && 
                         nextRow == food[foodIndex][0] && 
                         nextCol == food[foodIndex][1]);

        if (!eatsFood) {
            // If not eating, tail moves. Remove from body and set.
            pair<int, int> tail = snakeBody.back();
            snakeSet.erase(encode(tail.first, tail.second));
            snakeBody.pop_back();
        }

        // Check for self-collision (after potentially removing tail)
        if (snakeSet.count(encode(nextRow, nextCol))) {
            gameOver = true;
            return -1;
        }

        // Add new head
        snakeBody.push_front({nextRow, nextCol});
        snakeSet.insert(encode(nextRow, nextCol));

        if (eatsFood) {
            score++;
            foodIndex++;
        }

        return score;
    }
};

Design Snake Game in TypeScript

class SnakeGame {
    private width: number;
    private height: number;
    private food: number[][];
    private score: number;
    private foodIndex: number;
    private gameOver: boolean;
    private snakeBody: number[][]; // Deque of [row, col]
    private snakeSet: Set<string>; // Set of "row:col" for fast lookup
    private directions: { [key: string]: number[] };

    constructor(width: number, height: number, food: number[][]) {
        this.width = width;
        this.height = height;
        this.food = food;
        this.score = 0;
        this.foodIndex = 0;
        this.gameOver = false;

        // Snake body represented as an array, acting as a deque
        this.snakeBody = [[0, 0]];
        // Set for O(1) collision checks
        this.snakeSet = new Set<string>();
        this.snakeSet.add("0:0");

        this.directions = {
            'U': [-1, 0],
            'D': [1, 0],
            'L': [0, -1],
            'R': [0, 1]
        };
    }

    move(direction: string): number {
        if (this.gameOver) {
            return -1;
        }

        // Get current head position
        const head = this.snakeBody[0];
        const [dr, dc] = this.directions[direction];
        const nextRow = head[0] + dr;
        const nextCol = head[1] + dc;

        // Check for wall collision
        if (nextRow < 0 || nextRow >= this.height || nextCol < 0 || nextCol >= this.width) {
            this.gameOver = true;
            return -1;
        }

        // Check if snake eats food
        const eatsFood = (this.foodIndex < this.food.length &&
                          nextRow === this.food[this.foodIndex][0] &&
                          nextCol === this.food[this.foodIndex][1]);

        // If not eating, tail moves. Remove from body and set.
        if (!eatsFood) {
            const tail = this.snakeBody.pop()!;
            this.snakeSet.delete(`${tail[0]}:${tail[1]}`);
        }

        // Check for self-collision (after potentially removing tail)
        const nextHeadKey = `${nextRow}:${nextCol}`;
        if (this.snakeSet.has(nextHeadKey)) {
            this.gameOver = true;
            return -1;
        }

        // Add new head
        this.snakeBody.unshift([nextRow, nextCol]);
        this.snakeSet.add(nextHeadKey);

        if (eatsFood) {
            this.score++;
            this.foodIndex++;
        }

        return this.score;
    }
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.