Amplitude interview question
Implement the core logic of a Snake game with walls, growth and self-collision
- Company:
- Amplitude
- Round:
- Onsite
- Type:
- Coding
- Difficulty:
- Medium
- Reported:
- Q1 2026
Problem
Implement the game logic of Snake on a board with height rows and width columns. The snake starts with length 1 at a given cell start, written as (row, col). Apples appear one at a time at the positions listed in food, also given as (row, col): the next apple appears only after the current one is eaten.
Implement SnakeGame(width, height, start, food) and move(direction), where direction is one of "up", "down", "left" or "right" (the arrow keys). Each move advances the head by one cell:
- If the head leaves the board, the game is over.
- If the head lands on the current apple, the snake grows by one (its tail stays in place) and the score increases by 1.
- Otherwise the tail moves forward one cell.
- If the head runs into the snake's own body, the game is over.
move returns the score (apples eaten so far) after the move, or -1 if the game is over, including for every move after the game has ended.
The prompt does not settle two edge cases, so any consistent choice is accepted: whether the head may enter the cell that the tail leaves in the same move, and what happens when an apple appears on a cell covered by the snake. The examples below do not depend on either choice.
Example 1
Input: width = 4, height = 3, start = (0, 0), food = [(0, 2), (2, 3)]
moves: right, right, down, down, right, right
Output: 0, 1, 1, 1, 2, -1
The second move eats the apple at (0, 2), the fifth eats the apple at (2, 3), and the last move leaves the board.
Example 2
Input: width = 3, height = 3, start = (0, 0), food = [(0, 1), (0, 2), (1, 2), (1, 1)]
moves: right, right, down, left, up
Output: 1, 2, 3, 4, -1
After four apples the snake has length 5, and moving up puts the head on a body cell that is not the tail.
Constraints
widthandheightare at least 1, andstartlies on the board.- Aim for O(1) time per move.
Reported by candidates or drawn from publicly available sources, and rewritten in our own words. Pathwise Prep does not publish confidential assessment content. Report a concern