Implement Snake Game Moves With Food and Self-Collision

Last updated: November 29, 2026

Quick Overview

Design a Snake game on a width by height board: the snake starts at (0, 0) with length 1, food appears at given positions one after another, and move(direction) returns the score or -1 when the snake hits a wall or itself. Eating food grows the snake by one.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Technical Screen
Coding & Algorithms
Medium

0

0

0 solved


Design a Snake game on a width by height board: the snake starts at (0, 0) with length 1, food appears at given positions one after another, and move(direction) returns the score or -1 when the snake hits a wall or itself. Eating food grows the snake by one.

A Google technical screen design-and-simulate question. The interviewer checks that each move is O(1) using a deque for the body plus a set for occupancy, and that the tail-vacating subtlety (moving into the cell the tail just left is legal) is handled correctly.

What the Interviewer Expects
  • Store the body as a deque of cells with the head at one end
  • Keep a set of occupied cells for O(1) collision checks
  • Remove the tail before the self-collision check when not eating
  • Advance a food pointer and grow only when the head lands on food
  • Return -1 permanently after game over
Key Topics to Cover
simulation
deque
hash set
object-oriented design
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • What if food positions are random rather than given?
  • How would you render only the cells that changed per frame?
  • How would you support two snakes on one board?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

Board has width columns and height rows; cells are (row, col). food is a list of cells in the order they appear; only the current one is on the board. move(d) with d in U D L R returns the...

High-Level Design

State: body deque (head at the left), occupied set, food_idx, score, dead. On a move: compute the new head. If out of bounds, die. If the new head is the current food, grow: keep the tail an...


Submit Your Answer
Markdown supported