InternDoor

DSA · 1 min

Why your spiral matrix traversal is failing

Learn how to traverse a matrix in spiral order using top, bottom, left, and right bounds shifted inward after each side.

Practise DSAMore videos

The quiz

Print the matrix [[1, 2, 3], [4, 5, 6], [7, 8, 9]] in spiral order, starting at the top-left and moving right.

  1. 1 2 3 4 5 6 7 8 9
  2. 1 2 3 6 9 8 7 4 5
  3. 1 4 7 8 9 6 3 2 5
  4. 1 2 3 6 5 4 7 8 9
Show the answer

B. 1 2 3 6 9 8 7 4 5

Transcript

Most candidates mistakenly print row by row when asked for spiral matrix order.

To traverse a matrix in spiral order, peel it like layers: move right across the top, down the column, left, up, then repeat inside.

First go right for one two three, down for six nine, left for eight seven, then up to four and finally center at five.

Now the part most people miss: maintain four boundary pointers named top, right, bottom, and left, shifting each inward after completing its side.

Avoid printing values sequentially row by row. Track four bounds and apply boundary updates inward to peel each layer without repeating elements.

Pause and test yourself: what is the correct spiral order for this three by three matrix? Tap option A, B, C, or D now.

The correct answer is B. We move right along the top row, down, left, and up, then visit the remaining center element five.

Remember four shrinking bounds solve spiral traversal. Save this video before your interview, and practice more matrix problems on InternDoor right away.

More study videos

All videos
Learned it? See who is hiring

Engineering internships and entry-level jobs in India, newest first.