Snake in Matrix - Problem

Imagine a snake slithering through an n ร— n grid, following your commands! ๐Ÿ

The snake starts at the top-left corner (position 0) of the grid. Each cell in the grid has a unique position number calculated as: grid[i][j] = (i ร— n) + j. For example, in a 3ร—3 grid:

0 1 2
3 4 5
6 7 8

You'll receive a sequence of movement commands: "UP", "DOWN", "LEFT", and "RIGHT". The snake will faithfully follow each command, and it's guaranteed that the snake will never slither outside the grid boundaries.

Your task: Determine the final position number where the snake ends up after executing all commands.

Input & Output

example_1.py โ€” Python
$ Input: n = 2, commands = ["RIGHT", "DOWN"]
โ€บ Output: 3
๐Ÿ’ก Note: Snake starts at position 0 (0,0), moves RIGHT to position 1 (0,1), then DOWN to position 3 (1,1). Final position is 1ร—2 + 1 = 3.
example_2.py โ€” Python
$ Input: n = 3, commands = ["DOWN", "RIGHT", "UP"]
โ€บ Output: 1
๐Ÿ’ก Note: Snake starts at 0 (0,0), moves DOWN to 3 (1,0), RIGHT to 4 (1,1), then UP to 1 (0,1). Final position is 0ร—3 + 1 = 1.
example_3.py โ€” Python
$ Input: n = 1, commands = []
โ€บ Output: 0
๐Ÿ’ก Note: Edge case: With no commands, snake remains at starting position 0.

Visualization

Tap to expand
Snake Movement VisualizationStep 1: Grid Setup (n=3)012345678Step 2: Commands ["RIGHT", "DOWN"]012345678Step 3: Final Position = 1ร—3 + 1 = 4012345678Algorithm Steps:1. Initialize: row = 0, col = 02. Process "RIGHT": col = 1 โ†’ position = 0ร—3 + 1 = 13. Process "DOWN": row = 1 โ†’ position = 1ร—3 + 1 = 44. Return final position: 4
Understanding the Visualization
1
Start Position
Snake begins at the top-left corner (position 0)
2
Follow Commands
Process each movement command sequentially
3
Calculate Final Position
Convert final coordinates to position number
Key Takeaway
๐ŸŽฏ Key Insight: Converting between 2D grid coordinates and 1D position numbers is the core skill needed for grid-based problems like this one.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(m)

Where m is the number of commands - we process each command exactly once

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only need to store current row and column coordinates

n
2n
โœ“ Linear Space

Constraints

  • 2 โ‰ค n โ‰ค 10
  • 1 โ‰ค commands.length โ‰ค 100
  • commands[i] is one of "UP", "RIGHT", "DOWN", and "LEFT"
  • The snake will remain within the grid boundaries
Asked in
Google 25 Amazon 18 Meta 12 Microsoft 8
28.5K Views
Medium Frequency
~8 min Avg. Time
840 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