Snake in Matrix - Problem

There is a snake in an n x n matrix grid that 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 commands[i] is either "UP", "RIGHT", "DOWN", or "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 all commands.

Input & Output

Example 1 — Basic Movement
$ Input: n = 2, commands = ["RIGHT", "DOWN"]
Output: 3
💡 Note: Start at position 0 (row=0, col=0). Move RIGHT to (0,1). Move DOWN to (1,1). Final position = 1*2 + 1 = 3
Example 2 — Single Move
$ Input: n = 3, commands = ["DOWN", "RIGHT", "UP"]
Output: 1
💡 Note: Start at (0,0). DOWN to (1,0). RIGHT to (1,1). UP to (0,1). Final position = 0*3 + 1 = 1
Example 3 — Return to Start
$ Input: n = 2, commands = ["RIGHT", "LEFT"]
Output: 0
💡 Note: Start at (0,0). RIGHT to (0,1). LEFT back to (0,0). Final position = 0*2 + 0 = 0

Constraints

  • 1 ≤ n ≤ 103
  • 1 ≤ commands.length ≤ 104
  • commands[i] is either "UP", "RIGHT", "DOWN", or "LEFT"
  • The snake will remain within the grid boundaries

Visualization

Tap to expand
Snake in Matrix INPUT n x n Grid (n=2) 0 1 2 3 SNAKE Formula: grid[i][j] = (i*n) + j Input Values: n = 2 ["RIGHT","DOWN"] Commands sequence: RIGHT DOWN ALGORITHM STEPS 1 Initialize Position row=0, col=0 (cell 0) 2 Process "RIGHT" col++ --> row=0, col=1 3 Process "DOWN" row++ --> row=1, col=1 4 Calculate Final Cell (1*2)+1 = 3 Movement Trace: S E Start End Path UP:row-- DOWN:row++ LEFT:col-- RIGHT:col++ FINAL RESULT 0 1 2 3 Snake final position: row=1, col=1 Output: 3 Calculation: (1 * 2) + 1 = 3 OK - Position verified! Key Insight: Track snake position using (row, col) coordinates. For each command, update coordinates: UP: row-1, DOWN: row+1, LEFT: col-1, RIGHT: col+1. Final cell = (row * n) + col. Time: O(m) where m = commands length. Space: O(1) - only track two variables. TutorialsPoint - Snake in Matrix | Coordinate Tracking Approach
Asked in
Google 15 Microsoft 12 Amazon 8
12.0K Views
Medium Frequency
~8 min Avg. Time
450 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