DSA AnimatorREVISION VIDEOS
← Back to problems
New

Spiral Matrix II — LeetCode 59 video explanation

Given n, build an n by n matrix filled with the numbers 1 to n squared, in spiral order.

Loading videos…

DSA Animator › DSA Revision › Matrix › Spiral Matrix II

Key moments in the Spiral Matrix II video

0:03Problem0:10Example0:16Brute force0:23Key idea0:37Dry run0:51Code1:04Takeaway

What you will learn

Remember: the spiral writer is the spiral reader with a counter. Four sides, then shrink. The video solves Spiral Matrix II (LeetCode 59, Medium) with the Boundary Traversal pattern from the Matrix topic, and you can replay every step in the interactive Spiral Matrix II animation.

Spiral Matrix II video transcript

Problem

Given n, build an n by n matrix filled with the numbers 1 to n squared, in spiral order.

Example

For n equal to 3, the matrix is 1 2 3, then 8 9 4, then 7 6 5.

Brute force

This is Spiral Matrix in reverse: instead of reading in spiral order, you write. The same four boundaries make it simple.

Key idea

Keep a counter that starts at 1. Fill the top row left to right, the right column top to bottom, the bottom row right to left, and the left column bottom to top. Shrink each boundary after its side is filled, until the counter passes n squared.

Dry run

Fill the top row with 1, 2, 3. Fill down the right column with 4 and 5. Fill the bottom row backwards with 6 and 7. Fill up the left column with 8. Only the center is left, and it gets 9. The matrix is complete.

Code

In code, create an n by n array, and set the four boundaries. Loop while the counter is at most n squared. Fill each side, increasing the counter, and shrink that boundary. Every cell is written once, so it's O of n squared time.

Takeaway

Remember: the spiral writer is the spiral reader with a counter. Four sides, then shrink.

More Matrix revision videos

← All 185 DSA revision videos