Difficulty: Easy | Acceptance: 82.30% | Paid: No Topics: Array, String, Simulation
You are given a positive integer n, indicating that we have a square matrix of size n x n. You are also given a 0-indexed string array commands of length m, where commands[i] describes the ith command to perform.
The snake starts at cell (0, 0) of the matrix. Each command is one of the following strings:
“UP”: Move the snake one cell up. “DOWN”: Move the snake one cell down. “LEFT”: Move the snake one cell left. “RIGHT”: Move the snake one cell right.
The snake will not move outside the boundaries of the matrix. Return the final position of the snake after performing all commands.
- Examples
- Constraints
- Direct Simulation
- Direction Vector Map
Examples
Example 1:
Input: n = 2, commands = ["RIGHT","DOWN"]
Output: [1,1]
Explanation:
(0,0) -> (0,1) -> (1,1)
Example 2:
Input: n = 3, commands = ["DOWN","RIGHT","UP"]
Output: [0,1]
Explanation:
(0,0) -> (1,0) -> (1,1) -> (0,1)
Constraints
2 <= n <= 10
1 <= commands.length <= 100
commands[i] is one of "UP", "DOWN", "LEFT", "RIGHT".
The snake will not move outside the boundaries of the matrix.
Direct Simulation
Intuition We can iterate through the list of commands and update the snake’s row and column coordinates based on the current command string.
Steps
- Initialize row
rand columncto 0. - Iterate through each command in the
commandsarray. - If the command is “UP”, decrement
r. If “DOWN”, incrementr. - If the command is “LEFT”, decrement
c. If “RIGHT”, incrementc. - Return the final coordinates
[r, c].
class Solution:
def finalPositionOfSnake(self, n: int, commands: list[str]) -> list[int]:
r, c = 0, 0
for cmd in commands:
if cmd == "UP":
r -= 1
elif cmd == "DOWN":
r += 1
elif cmd == "LEFT":
c -= 1
elif cmd == "RIGHT":
c += 1
return [r, c]Complexity
- Time: O(m), where m is the number of commands.
- Space: O(1), only using a few variables for coordinates.
- Notes: Simple and readable, but requires multiple conditional checks per command.
Direction Vector Map
Intuition Instead of using multiple conditional statements, we can map each command string to a coordinate change vector (delta row, delta column). This makes the code cleaner and easier to extend.
Steps
- Create a map/dictionary where keys are command strings (“UP”, “DOWN”, etc.) and values are pairs representing row and column changes (e.g., “UP” -> [-1, 0]).
- Initialize
randcto 0. - Iterate through commands. For each command, look up the vector and add the values to
randc. - Return
[r, c].
class Solution:
def finalPositionOfSnake(self, n: int, commands: list[str]) -> list[int]:
moves = {
"UP": (-1, 0),
"DOWN": (1, 0),
"LEFT": (0, -1),
"RIGHT": (0, 1)
}
r, c = 0, 0
for cmd in commands:
dr, dc = moves[cmd]
r += dr
c += dc
return [r, c]Complexity
- Time: O(m), where m is the number of commands.
- Space: O(1), the map size is constant (4 entries).
- Notes: More elegant than if-else chains, reduces boilerplate code.