Design Snake Game - Problem

๐Ÿ Design Snake Game

Design and implement the classic Snake Game that runs on a device with screen dimensions height ร— width. If you're not familiar with Snake, it's a simple but addictive game where a snake moves around the screen eating food and growing longer!

Game Rules:

  • ๐Ÿ The snake starts at position (0, 0) (top-left corner) with length 1
  • ๐ŸŽ Food appears one piece at a time at predetermined locations
  • ๐Ÿ“ˆ When the snake eats food, both its length and score increase by 1
  • ๐Ÿ’€ Game ends if the snake hits a wall or collides with itself
  • ๐ŸŽฏ Return the current score after each move, or -1 if game over

Your task: Implement the SnakeGame class with:

  • SnakeGame(int width, int height, int[][] food) - Initialize the game
  • int move(String direction) - Move snake and return score (or -1 if game over)

Directions: "U" (up), "D" (down), "L" (left), "R" (right)

Input & Output

example_1.py โ€” Basic Snake Movement
$ Input: SnakeGame(3, 2, [[1,2],[0,1]]) snake.move("R") # Move right snake.move("D") # Move down snake.move("R") # Move right (eat food) snake.move("U") # Move up (eat food) snake.move("L") # Move left snake.move("U") # Move up (hit wall)
โ€บ Output: 0 0 1 2 2 -1
๐Ÿ’ก Note: Snake moves through the 3x2 grid. Score increases when food is eaten at (1,2) and (0,1). Game ends when snake tries to move up from row 0 (out of bounds).
example_2.py โ€” Self Collision
$ Input: SnakeGame(3, 3, [[2,0]]) snake.move("D") # Move down snake.move("D") # Move down (eat food) snake.move("U") # Move up snake.move("U") # Move up (hit itself)
โ€บ Output: 0 1 1 -1
๐Ÿ’ก Note: Snake grows after eating food at (2,0). When it tries to move back up, it collides with its own body segment, ending the game.
example_3.py โ€” Empty Food Array
$ Input: SnakeGame(2, 2, []) snake.move("R") # Move right snake.move("D") # Move down snake.move("L") # Move left snake.move("U") # Move up (back to start)
โ€บ Output: 0 0 0 0
๐Ÿ’ก Note: No food available, so snake maintains length 1 and score stays 0. Snake moves in a square pattern without growing.

Visualization

Tap to expand
Snake Game ArchitectureGame GridDeque (Body)Head โ†’ (0,0) โ†’ (1,0) โ†’ Tailโ€ข addFirst() - O(1)โ€ข removeLast() - O(1)โ€ข Size trackingHash Set (Positions){"0,0", "1,0", "2,0"}โ€ข contains() - O(1)โ€ข add() - O(1)โ€ข remove() - O(1)Move Algorithm1. Calculate new head position2. Check bounds & collision (hash lookup)3. Update deque & hash set4. Return score or -1Snake HeadSnake BodyFood
Understanding the Visualization
1
Initialize Game
Start with snake head at (0,0), empty food queue, score = 0
2
Process Move
Calculate new head position based on direction
3
Validate Move
Check bounds and collision using hash set O(1) lookup
4
Update Snake
Add new head, conditionally remove tail, sync data structures
5
Return Score
Return current score or -1 if game over
Key Takeaway
๐ŸŽฏ Key Insight: Combining deque for efficient queue operations with hash set for instant collision detection creates an optimal O(1) solution that scales perfectly for competitive gaming scenarios.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(1)

Each move operation is O(1) - hash set lookup, deque operations are all constant time

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Store snake coordinates in both deque and hash set, where n is snake length

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค width, height โ‰ค 104
  • 0 โ‰ค food.length โ‰ค 50
  • food[i].length == 2
  • 0 โ‰ค ri < height
  • 0 โ‰ค ci < width
  • direction.length == 1
  • direction is one of {'U', 'D', 'L', 'R'}
  • At most 104 calls will be made to move
Asked in
Google 45 Amazon 38 Meta 32 Apple 28 Microsoft 25
67.2K Views
High Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen