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: Position Tracking012345678Commands: ["RIGHT", "DOWN", "LEFT"]Start: position 0 (row=0, col=0)RIGHT: position 1 (row=0, col=1)DOWN: position 4 (row=1, col=1)LEFT: position 3 (row=1, col=0)Final position: 3
Understanding the Visualization
1
Input
Grid size n=3, commands=["RIGHT","DOWN","LEFT"]
2
Process
Snake follows commands starting from position 0
3
Output
Final position where snake ends up
Key Takeaway
🎯 Key Insight: Track coordinates directly instead of converting position repeatedly
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