Spiral Matrix - JS Solution

JS
Editorial

Solution explanation

Solution explanation

Approach

The matrix is traversed layer by layer in a spiral pattern using four boundaries: top, bottom, left, and right. Each boundary represents the outermost row or column that has not yet been completely processed. As elements along one boundary are visited, that boundary moves inward to exclude the completed layer.

  • Boundary definitions:
    • Top: Index of the first row that has not yet been fully traversed.
    • Bottom: Index of the last row that has not yet been fully traversed.
    • Left: Index of the first column that has not yet been fully traversed.
    • Right: Index of the last column that has not yet been fully traversed.
  • Initialization: Set top = 0, bottom = m − 1, left = 0, and right = n − 1, where m and n are the number of rows and columns respectively.
  • Main Loop: Continue while both top ≤ bottom and left ≤ right hold — meaning there are still unprocessed cells within the current boundary region.
    1. Left → Right: Traverse the topmost remaining row, then increment top to exclude it.
    2. Top → Bottom: Traverse the rightmost remaining column, then decrement right to exclude it.
    3. Right → Left: Traverse the bottom row only if top ≤ bottom still holds — meaning there are still unprocessed rows after moving the top boundary upward. Then decrement bottom to exclude that row.
    4. Bottom → Top: Traverse the leftmost column only if left ≤ right still holds — meaning there are still unprocessed columns after moving the right boundary leftward. Then increment left to exclude that column.
  • Why the boundary checks matter: After each directional traversal, the corresponding boundary moves inward. The conditions top ≤ bottom and left ≤ right ensure that we do not revisit any already-processed rows or columns. Once a boundary crosses its opposite, it means all cells in that dimension have been fully covered.
  • Result: When the loop finishes, all elements have been collected in spiral order and stored in the output list.

Time Complexity

Each cell is visited exactly once, so the running time is O(m × n), where m is the number of rows and n is the number of columns in the matrix.

Space Complexity

Auxiliary space is O(1). If you include the output array, total space is O(m × n)

Visucodize editorial solution titled JS Solution for LeetCode's Spiral Matrix coding problem. Includes code and may include explanation. You can animate the code step by step using the provided input by clicking the run button, or fork it locally to update the code and input for custom visualization. View the original problem at https://leetcode.com/problems/spiral-matrix.