Spiral Matrix III

MediumMatrixsimulation

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You stand on cell (rStart, cStart) of a rows x cols grid, initially facing east. You walk an ever-growing clockwise spiral: 1 step east, 1 step south, 2 steps west, 2 steps north, 3 steps east, 3 steps south, and so on (the run length grows by one after every two turns). The walk may leave the grid and later return. Record each grid cell the moment you first stand on it (the starting cell is recorded first); cells outside the grid are ignored. Stop once all rows * cols cells are recorded. Return the recorded cells as a list of [row, col] pairs in visiting order.

Examples

Input: rows = 1, cols = 4, rStart = 0, cStart = 0
Output: [[0,0],[0,1],[0,2],[0,3]]
Only the eastward runs touch the grid, visiting the row left to right.
Input: rows = 3, cols = 3, rStart = 1, cStart = 1
Output: [[1,1],[1,2],[2,2],[2,1],[2,0],[1,0],[0,0],[0,1],[0,2]]
Starting from the center, the first ring of the spiral covers the whole 3x3 grid.

Constraints

  • `1 <= rows, cols <= 100`
  • `0 <= rStart < rows`
  • `0 <= cStart < cols`

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More simulation problems