Spiral Matrix – Solution & Complexity
Solution Walkthrough
Step 1: Understand the Spiral Fill
- Create an
n x nmatrix and place values from1ton². - The direction starts moving right, then turns down, left, and up.
- After each side is filled, the active boundary moves inward.
- Create an
Step 2: Track Four Boundaries
- Keep
top,bottom,left, andrightboundaries for the unfilled rectangle. - Fill the top row left-to-right, then move
topdown. - Fill the right column top-to-bottom, then move
rightleft, and continue around.
- Keep
Step 3: Fill One Ring at a Time
- One loop iteration fills the outer ring of the current rectangle.
- After a ring is finished, the boundaries describe the next inner ring.
- Continue while
top <= bottomandleft <= right.
Step 4: Handle Center Cells and Input Type
- Odd-sized matrices eventually have a single center cell, which the boundary loop fills naturally.
- Some test inputs may provide
nas a string after JSON parsing. - Convert
nto an integer before creating the matrix.
Step 5: Complete Solution and Complexity
- The final solution fills each cell exactly once while shrinking the boundaries.
- Time complexity is O(n²).
- Space complexity is O(n²) for the returned matrix.