Skip to main content

Leetcode 59: Spiral Matrix II


1. Problem Statement (Simple Explanation)


You’re given a positive integer n.

You must generate an n x n matrix filled with the numbers 1 to n², in spiral order:

  • Start from the top-left, go right, then down, then left, then up, and so on, spiraling inward.


2. Examples


Example 1:



Input: n = 3

Output:

[

  [1,2,3],

  [8,9,4],

  [7,6,5]

]

Filled in spiral from 1 to 9.


Example 2:


Input: n = 1

Output:

[

  [1]

]


3. Approach – Boundary Tracking (Same Concept as Spiral Matrix I)


We use four boundaries:

  • top – current top row index

  • bottom – current bottom row index

  • left – current left column index

  • right – current right column index

And a counter num from 1 to n*n.

While top <= bottom and left <= right:

  1. Fill top row from left to right. Increment top.

  2. Fill right column from top to bottom. Decrement right.

  3. If top <= bottom, fill bottom row from right to left. Decrement bottom.

  4. If left <= right, fill left column from bottom to top. Increment left.


Pseudo-code:



Complexity:

  • Time: We fill each cell once → O(n2)

  • Space: O(n2) for the matrix (required output), extra variables are O(1)


4. Java code



5. C code



6. C++ code



7. Python code



8. JavaScript code



Comments