Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Build confidence with an intuition-first walkthrough focused on array fundamentals.
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 summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array
2 ["RIGHT","DOWN"]
3 ["DOWN","RIGHT","UP"]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3248: Snake in Matrix
class Solution {
public int finalPositionOfSnake(int n, List<String> commands) {
int x = 0, y = 0;
for (var c : commands) {
switch (c.charAt(0)) {
case 'U' -> x--;
case 'D' -> x++;
case 'L' -> y--;
case 'R' -> y++;
}
}
return x * n + y;
}
}
// Accepted solution for LeetCode #3248: Snake in Matrix
func finalPositionOfSnake(n int, commands []string) int {
x, y := 0, 0
for _, c := range commands {
switch c[0] {
case 'U':
x--
case 'D':
x++
case 'L':
y--
case 'R':
y++
}
}
return x*n + y
}
# Accepted solution for LeetCode #3248: Snake in Matrix
class Solution:
def finalPositionOfSnake(self, n: int, commands: List[str]) -> int:
x = y = 0
for c in commands:
match c[0]:
case "U":
x -= 1
case "D":
x += 1
case "L":
y -= 1
case "R":
y += 1
return x * n + y
// Accepted solution for LeetCode #3248: Snake in Matrix
/**
* [3248] Snake in Matrix
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn final_position_of_snake(n: i32, commands: Vec<String>) -> i32 {
let (mut x, mut y) = (0, 0);
commands.iter().for_each(|str| match str.as_str() {
"UP" => x -= 1,
"DOWN" => x += 1,
"LEFT" => y -= 1,
"RIGHT" => y += 1,
_ => {}
});
x * n + y
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_3248() {
assert_eq!(
3,
Solution::final_position_of_snake(2, vec_string!("RIGHT", "DOWN"))
);
assert_eq!(
1,
Solution::final_position_of_snake(3, vec_string!("DOWN", "RIGHT", "UP"))
);
}
}
// Accepted solution for LeetCode #3248: Snake in Matrix
function finalPositionOfSnake(n: number, commands: string[]): number {
let [x, y] = [0, 0];
for (const c of commands) {
c[0] === 'U' && x--;
c[0] === 'D' && x++;
c[0] === 'L' && y--;
c[0] === 'R' && y++;
}
return x * n + y;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.