const solve = (nums) => { let left = 0, right = nums.length - 1; while (left < right) { const sum = nums[left] + nums[right]; if (sum === target) return [left, right]; }}
Problem Walkthrough

Spiral Matrix LeetCode Solution: Boundary Approach

Spiral Matrix (#54) is pure boundary management — no fancy algorithms, just four pointers and careful shrinking. Here is exactly how to implement it cleanly every time.

8 min read|

Spiral Matrix (#54): boundary management, not algorithms

Four boundaries, shrink inward — the matrix traversal pattern every interviewer knows

Spiral Matrix: No Algorithms, Just Boundaries

Spiral Matrix (#54) is one of those problems that trips people up not because it requires a clever algorithm, but because it demands careful bookkeeping. There is no dynamic programming, no graph traversal, no binary search. The entire solution boils down to managing four boundary variables and knowing when to stop.

The spiral matrix leetcode problem asks you to return all elements of an m x n matrix in spiral order — starting from the top-left corner, moving right across the top row, down the right column, left across the bottom row, up the left column, and then repeating inward. It sounds simple, and the core idea genuinely is simple. The challenge is implementing it without off-by-one errors or double-counting.

This walkthrough covers the boundary approach from intuition to implementation, walks through a visual example step by step, and highlights the edge cases that cause most bugs. By the end, you will have a clean template you can apply to Spiral Matrix and its companion problem, Spiral Matrix II (#59).

Understanding the Spiral Matrix Problem

Given an m x n matrix, return all elements in spiral order. For a 3x3 matrix like [[1,2,3],[4,5,6],[7,8,9]], the expected output is [1,2,3,6,9,8,7,4,5]. You start at position (0,0), traverse the entire outer ring clockwise, then move inward and repeat.

The leetcode 54 solution needs to handle matrices of any shape — square, wide, tall, single row, single column, and even 1x1. This is not just a square-matrix problem, and assuming it is leads to the most common bugs candidates write in interviews.

What makes this problem interesting is that there is essentially one approach that works well. Unlike problems with multiple valid strategies (BFS vs DFS, two pointers vs hash map), spiral order matrix traversal is best solved with the boundary technique. The question is purely about implementation quality.

ℹ️

Interview Insight

Spiral Matrix (#54) is one of the most-asked matrix problems at Amazon and Microsoft — it tests careful boundary management, not algorithmic knowledge.

The Boundary Approach: Four Pointers, Shrink Inward

The boundary approach uses four variables — top, bottom, left, and right — to define the current unvisited rectangle within the matrix. Initially, top = 0, bottom = rows - 1, left = 0, and right = cols - 1. Each iteration of the main loop traverses the four edges of this rectangle and then shrinks the boundaries inward.

The matrix boundary traversal works in four steps per layer. First, traverse the top row from left to right, then increment top. Second, traverse the right column from top to bottom, then decrement right. Third, traverse the bottom row from right to left (if top <= bottom still holds), then decrement bottom. Fourth, traverse the left column from bottom to top (if left <= right still holds), then increment left.

The loop continues while top <= bottom AND left <= right. When these conditions fail, every element has been visited. The beauty of this approach is that it naturally handles matrices of any dimension — the boundary checks prevent over-traversal on non-square inputs.

  • Initialize: top = 0, bottom = m-1, left = 0, right = n-1
  • Traverse right along top row, then top++
  • Traverse down along right column, then right--
  • If top <= bottom: traverse left along bottom row, then bottom--
  • If left <= right: traverse up along left column, then left++
  • Repeat while top <= bottom AND left <= right

Spiral Matrix Implementation

The implementation translates directly from the boundary approach. Create a result array, set up the four boundary variables, and run a while loop. Inside the loop, four for-loops handle each edge traversal, with boundary updates between them.

For the spiral matrix leetcode solution, the right-to-left and bottom-to-top traversals need guard conditions. After traversing right and down, check if top <= bottom before traversing left. After traversing left, check if left <= right before traversing up. These two checks are the difference between a correct solution and one that fails on non-square matrices.

Time complexity is O(m * n) because you visit every element exactly once. Space complexity is O(1) excluding the output array — the only extra storage is the four boundary integers. This is optimal for the problem since you must read every element at least once.

  1. 1Create an empty result array and set top=0, bottom=m-1, left=0, right=n-1
  2. 2While top <= bottom and left <= right, enter the main loop
  3. 3Traverse top row: for i from left to right, push matrix[top][i]. Increment top.
  4. 4Traverse right column: for i from top to bottom, push matrix[i][right]. Decrement right.
  5. 5Check if top <= bottom. If yes, traverse bottom row: for i from right to left, push matrix[bottom][i]. Decrement bottom.
  6. 6Check if left <= right. If yes, traverse left column: for i from bottom to top, push matrix[i][left]. Increment left.
  7. 7Return result array.
💡

Pro Tip

The key implementation detail: after traversing right and down, re-check if top<=bottom before traversing left, and if left<=right before traversing up. This prevents double-counting on single rows/columns.

Visual Walkthrough: 3x3 Step by Step

Let us walk through a 3x3 matrix: [[1,2,3],[4,5,6],[7,8,9]]. Initial boundaries: top=0, bottom=2, left=0, right=2.

Layer 1, traverse right: collect 1, 2, 3 from row 0. Set top=1. Traverse down: collect 6, 9 from column 2. Set right=1. Check top(1) <= bottom(2): yes. Traverse left: collect 8, 7 from row 2. Set bottom=1. Check left(0) <= right(1): yes. Traverse up: collect 4 from column 0. Set left=1.

Layer 2: top=1, bottom=1, left=1, right=1. Traverse right: collect 5 from row 1. Set top=2. Now top(2) > bottom(1), so the while condition fails. The loop ends. Result: [1, 2, 3, 6, 9, 8, 7, 4, 5]. This matches the expected spiral order matrix output perfectly.

Notice how the boundary checks naturally handled the center element. The inner rectangle collapsed to a single cell, the right traversal picked it up, and the loop terminated before any double-counting could occur.

Edge Cases and Spiral Matrix II

The most important edge cases for spiral matrix explained clearly: a single row (1xn) should just return all elements left to right. A single column (mx1) should return all elements top to bottom. A 1x1 matrix returns that single element. All of these work correctly with the boundary approach because the guard conditions prevent unnecessary traversals.

Non-square matrices like 2x4 or 4x2 are where most implementations break. Consider a 2x4 matrix. After the first complete layer (right, down, left, up), the remaining submatrix might be a single row. Without the inner boundary checks after traversing right and down, you would traverse that row twice — once going left and once incorrectly going right again.

Spiral Matrix II (#59) is the reverse problem — instead of reading elements in spiral order, you fill a matrix with values 1 to n*n in spiral order. The same boundary approach applies identically. The only difference is that instead of pushing matrix[row][col] to a result array, you assign matrix[row][col] = counter and increment the counter. If you master the boundary technique for #54, #59 is essentially free.

  • 1x1 matrix: returns single element immediately
  • Single row (1xn): right traversal collects all elements, loop ends
  • Single column (mx1): right collects one element, down collects the rest
  • Non-square (e.g., 2x4): inner boundary checks prevent double-counting
  • Spiral Matrix II (#59): same boundary approach, write instead of read
⚠️

Watch Out

Non-square matrices (e.g., 2x4) are the trickiest edge case — the inner boundary checks after the first two traversals are essential. Without them, you'll process the last row or column twice.

What Spiral Matrix Teaches You

Spiral Matrix is not an algorithm problem — it is a simulation and boundary management problem. The skill it tests is your ability to translate a clear visual process into clean, bug-free code. Interviewers use it precisely because the concept is simple but the implementation has multiple failure points.

The boundary management pattern appears in other matrix problems too. Rotate Image (#48) manipulates layers from outside in. Set Matrix Zeroes (#73) requires tracking row and column boundaries. Game of Life (#289) processes cells layer by layer. Getting comfortable with boundary pointers and layer-by-layer processing pays dividends across many matrix traversal spiral problems.

Practice spiral matrix and similar boundary problems with YeetCode flashcards to build the muscle memory for these traversal patterns. The pattern is simple enough to memorize, but the edge cases require repeated practice to handle confidently under interview pressure. Drill it until the four-pointer setup and the inner boundary checks are automatic.

Ready to master algorithm patterns?

YeetCode flashcards help you build pattern recognition through active recall and spaced repetition.

Start practicing now