DSA · Patterns, not puzzles
How do you traverse a matrix?
Short answer
Use nested loops for row-major or column-major access, and boundary pointers for spiral order. For grid search, treat each cell as a graph node and use BFS or DFS with a visited set.
Most matrix problems are either index arithmetic or graph traversal in disguise. Clarify whether rows and columns can have different lengths, whether movement is four-directional or eight-directional, and whether the matrix can be modified in place.
function spiralOrder(matrix) {
if (matrix.length === 0) return [];
const result = [];
let top = 0;
let bottom = matrix.length - 1;
let left = 0;
let right = matrix[0].length - 1;
while (top <= bottom && left <= right) {
for (let col = left; col <= right; col++) result.push(matrix[top][col]);
top += 1;
for (let row = top; row <= bottom; row++) result.push(matrix[row][right]);
right -= 1;
if (top <= bottom) {
for (let col = right; col >= left; col--) result.push(matrix[bottom][col]);
bottom -= 1;
}
if (left <= right) {
for (let row = bottom; row >= top; row--) result.push(matrix[row][left]);
left += 1;
}
}
return result;
}Patterns to recognise
- Row-major scan: outer loop over rows, inner loop over columns
- Spiral: maintain top, bottom, left and right boundaries
- Diagonal: row and column indices move together or in opposite directions
- Grid BFS or DFS: generate neighbours from four directions
- In-place rotation: transpose, then reverse rows or columns
A common bug is assuming a square matrix. Always use matrix.length for rows and matrix[0].length for columns, and handle an empty matrix before reading the first row.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1How do you rotate a matrix in place?
- 2How do you traverse a matrix diagonally?
- 3Why are boundary checks needed in spiral traversal?
- 4How would you find the number of islands in a grid?
Say it in the interview
For simple scans I use nested loops and keep rows and columns separate because the matrix may not be square. For spiral order I maintain four shrinking boundaries and check them before the bottom and left passes. For grid search I treat cells as graph nodes and use BFS or DFS with a visited set. I always handle an empty matrix and clarify the movement rules first.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live DSA mock interview and get scored feedback on depth, clarity and confidence.