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 <= 101 <= commands.length <= 100commands consists only of "UP", "RIGHT", "DOWN", and "LEFT".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.
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.
Time Complexity: O(m), where m is the number of commands.
Space Complexity: O(1) since only fixed variables are used for position tracking.
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.
Time Complexity: O(m), where m is the command count.
Space Complexity: O(1), only a few variables are needed for computation.
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).
Python
Java
C++
Go
TypeScript
| Approach | Complexity |
|---|---|
| Coordinate Mapping Approach | Time Complexity: |
| Vector Approach | Time Complexity: |
| Simulation | — |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Coordinate Mapping Approach | O(k) | O(1) | Best for simple grid simulations where row and column tracking is enough |
| Direction Vector Approach | O(k) | O(1) | Cleaner implementation when working with multiple directions or reusable grid movement logic |
LeetCode 3248 | easy | Snake in Matrix | Python code explanation • Techtonic Knights • 728 views views
Watch 9 more video solutions →Practice Snake in Matrix with our built-in code editor and test cases.
Practice on FleetCode