Skip to main content

Snake in Matrix - Solution & Explanation

EasyArrayStringSimulation15 min readAsked at: Google
Practice this problem

Problem Statement

There is a snake in an n x n matrix grid and can move in four possible directions. Each cell in the grid is identified by the position: grid[i][j] = (i * n) + j.

The snake starts at cell 0 and follows a sequence of commands.

You are given an integer n representing the size of the grid and an array of strings commands where each command[i] is either "UP", "RIGHT", "DOWN", and "LEFT". It's guaranteed that the snake will remain within the grid boundaries throughout its movement.

Return the position of the final cell where the snake ends up after executing commands.

 

Example 1:

Input: n = 2, commands = ["RIGHT","DOWN"]

Output: 3

Explanation:

0 1
2 3
0 1
2 3
0 1
2 3

Example 2:

Input: n = 3, commands = ["DOWN","RIGHT","UP"]

Output: 1

Explanation:

0 1 2
3 4 5
6 7 8
0 1 2
3 4 5
6 7 8
0 1 2
3 4 5
6 7 8
0 1 2
3 4 5
6 7 8

 

Constraints:

  • 2 <= n <= 10
  • 1 <= commands.length <= 100
  • commands consists only of "UP", "RIGHT", "DOWN", and "LEFT".
  • The input is generated such the snake will not move outside of the boundaries.

Approach Overview

Problem Overview: You start with a snake at the top-left corner of an n x n matrix (cell index 0). A list of movement commands such as UP, DOWN, LEFT, and RIGHT is given. After applying each move, return the final cell number assuming the matrix is indexed in row-major order.

Approach 1: Coordinate Mapping Approach (O(k) time, O(1) space)

Track the snake’s position using two integers: row and col. Initialize both to 0. Iterate through the command list and update coordinates based on the direction: decrement row for UP, increment row for DOWN, decrement col for LEFT, and increment col for RIGHT. After processing all moves, convert the 2D position into the matrix’s linear index using row * n + col. The key insight is that the matrix numbering follows row-major order, so a simple arithmetic mapping gives the final answer without storing the grid.

This method is a straightforward simulation. Each command results in a constant-time coordinate update. No extra data structures are required, making the space complexity O(1). This approach is easy to implement and works efficiently even for large command lists.

Approach 2: Direction Vector Approach (O(k) time, O(1) space)

Instead of multiple condition checks, store movement offsets in a direction map. For example, map each command to a vector: UP (-1,0), DOWN (1,0), LEFT (0,-1), and RIGHT (0,1). Iterate through the commands and update the current position using these vectors. This reduces branching logic and keeps the movement rules centralized.

The vector-based solution is common in grid traversal problems involving arrays and directional movement. Each iteration performs a constant-time vector addition to update the coordinates, keeping time complexity at O(k) where k is the number of commands. Space remains O(1) since only a few variables and a small direction map are used.

Recommended for interviews: The Coordinate Mapping approach is usually what interviewers expect first. It shows you understand how row-major indexing works and can simulate movement in a grid efficiently. The Direction Vector approach is slightly cleaner and scales better when more directions or movement rules are added. Demonstrating both shows strong understanding of string-driven simulations and grid traversal patterns.

Approach 1: Coordinate Mapping Approach

This approach leverages the understanding that each movement updates either the row or column of the snake's position. We keep track of the current position as coordinates (x, y) and apply transformations based on each command. Finally, convert the coordinates back to the one-dimensional index.

This C solution declares initial coordinates (x, y), with starting position at the top-left corner (0, 0). Based on the command, it adjusts either the x or y value. After processing all commands, it converts the coordinates back to a single index using x * n + y.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(m), where m is the number of commands.
Space Complexity: O(1) since only fixed variables are used for position tracking.

Try this approach in the editor →

Approach 2: Vector Approach

This approach represents movement directional changes as vectors (changes in the coordinate positions). The commands map to these vectors which modify the position cumulatively. This approach simplifies direction handling and makes calculations straightforward.

This C solution defines direction vectors for each movement which are added to the current coordinates (x, y). After executing all commands, it calculates the final cell index and returns it.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(m), where m is the command count.
Space Complexity: O(1), only a few variables are needed for computation.

Try this approach in the editor →

Approach 3: Simulation

We can use two variables x and y to represent the position of the snake. Initially, x = y = 0. Then, we traverse commands and update the values of x and y based on the current command. Finally, we return x times n + y.

The time complexity is O(n), where n is the length of the array commands. The space complexity is O(1).

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Coordinate Mapping Approach

Time Complexity: O(m), where m is the number of commands.
Space Complexity: O(1) since only fixed variables are used for position tracking.

Vector Approach

Time Complexity: O(m), where m is the command count.
Space Complexity: O(1), only a few variables are needed for computation.

Simulation

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Coordinate Mapping ApproachO(k)O(1)Best for simple grid simulations where row and column tracking is enough
Direction Vector ApproachO(k)O(1)Cleaner implementation when working with multiple directions or reusable grid movement logic

Video Solution

LeetCode 3248 | easy | Snake in Matrix | Python code explanationTechtonic Knights728 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Snake in Matrix easy or hard?
Snake in Matrix is categorized as an Easy problem. It mainly tests basic grid simulation, coordinate updates, and understanding of row-major indexing. The optimal solution is straightforward and runs in linear time with constant space.
Snake in Matrix Python/Java solution
The implementation is identical across languages. Maintain row and column variables, iterate through the command list, update coordinates for each direction, and compute the final index using row * n + col. This approach works in Python, Java, C++, JavaScript, and C#.
How to solve Snake in Matrix in O(k)?
Initialize row = 0 and col = 0 to represent the starting cell. Iterate through the command list and update the coordinates based on the direction. After processing all moves, compute the final index using row * n + col. This single pass over the commands gives an O(k) time solution.
What is the best approach for Snake in Matrix?
The coordinate mapping simulation is the most common solution. Track the snake’s row and column while processing each direction command, then convert the final position to a linear index using row * n + col. This runs in O(k) time with O(1) space where k is the number of moves.
Is Snake in Matrix asked at Google/Amazon/Meta?
Snake in Matrix is primarily a LeetCode-style simulation problem rather than a frequently reported FAANG interview question. However, similar grid simulation and coordinate tracking problems appear in interviews at companies like Amazon and Google.
What data structure is used in Snake in Matrix?
The solution mainly uses primitive variables to track row and column coordinates. Some implementations also use a small direction map or vector table to convert commands into movement offsets. No complex data structures are required.
What is the time complexity of Snake in Matrix?
The time complexity is O(k), where k is the number of movement commands. Each command results in a constant-time coordinate update. Space complexity remains O(1) since only the current row and column are stored.

Ready to solve this problem?

Practice Snake in Matrix with our built-in code editor and test cases.

Practice on FleetCode