DSA AnimatorREVISION VIDEOS
← Back to problems
New

Spiral Matrix — LeetCode 54 video explanation

Return all the elements of a matrix in spiral order. Go right along the top, down the right side, left along the bottom, and up the left side, then repeat inward.

Loading videos…

DSA Animator › DSA Revision › Matrix › Spiral Matrix

Key moments in the Spiral Matrix video

0:03Problem0:13Example0:21Brute force0:30Key idea0:46Dry run1:03Code1:23Takeaway

What you will learn

Remember: four boundaries, four walks, shrink after each. Re-check the boundaries before walking back. The video solves Spiral Matrix (LeetCode 54, Medium) with the Boundary Traversal pattern from the Matrix topic, and you can replay every step in the interactive Spiral Matrix animation.

Spiral Matrix video transcript

Problem

Return all the elements of a matrix in spiral order. Go right along the top, down the right side, left along the bottom, and up the left side, then repeat inward.

Example

For this 3 by 4 matrix, the spiral order is 1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7.

Brute force

Simulating with a direction and a visited grid works, but needs extra space and careful turning rules. Four shrinking boundaries are simpler.

Key idea

Keep four boundaries: top, bottom, left and right. Walk the top row, then move top down. Walk the right column, then move right in, and do the same for the bottom row and the left column. Before the bottom and left walks, check that the boundaries have not crossed.

Dry run

Walk the top row: 1, 2, 3, 4. Walk down the right column: 8 and 12. Walk the bottom row backwards: 11, 10, 9. Walk up the left column: 5. Now only the middle row is left: 6 and 7. The boundaries cross, so we stop with 12 numbers.

Code

In code, set the four boundaries. While top is not below bottom and left is not past right, walk the four sides. After each side, move that boundary inward. Check the boundaries again before the bottom row and the left column, so a single row or column is not read twice. Every element is visited once, so it's O of m times n time.

Takeaway

Remember: four boundaries, four walks, shrink after each. Re-check the boundaries before walking back.

More Matrix revision videos

← All 185 DSA revision videos