Programming & Development / April 8, 2025

LeetCode 54: Spiral Matrix in Go – Clean Traversal with Layer-by-Layer Logic

Go Golang LeetCode Spiral Matrix Matrix Traversal 2D Array Directional Movement Interview Questions Matrix Bounds Time Complexity O(mn)

Introduction

LeetCode 54: Spiral Matrix is a neat array traversal problem where the goal is to return all elements of a 2D matrix in spiral order. This kind of problem is commonly asked in coding interviews to test understanding of boundaries, matrix dimensions, and directional iteration.

Problem Statement

Given an m x n matrix, return all elements of the matrix in spiral order.

Example:

go

Input: matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]

Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]

Constraints

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 10
  • -100 <= matrix[i][j] <= 100

Approach: Layer-by-Layer Traversal

To move in a spiral, we simulate the movement by using four pointers:

  • top – starting row
  • bottom – ending row
  • left – starting column
  • right – ending column

We loop until top > bottom or left > right, and traverse in this order:

  1. Left to Right (Top Row)
  2. Top to Bottom (Right Column)
  3. Right to Left (Bottom Row) – if still in bounds
  4. Bottom to Top (Left Column) – if still in bounds

Go Implementation

go

func spiralOrder(matrix [][]int) []int {
    if len(matrix) == 0 {
        return []int{}
    }

    top, bottom := 0, len(matrix)-1
    left, right := 0, len(matrix[0])-1
    result := []int{}

    for top <= bottom && left <= right {
        // Left to Right
        for col := left; col <= right; col++ {
            result = append(result, matrix[top][col])
        }
        top++

        // Top to Bottom
        for row := top; row <= bottom; row++ {
            result = append(result, matrix[row][right])
        }
        right--

        // Right to Left
        if top <= bottom {
            for col := right; col >= left; col-- {
                result = append(result, matrix[bottom][col])
            }
            bottom--
        }

        // Bottom to Top
        if left <= right {
            for row := bottom; row >= top; row-- {
                result = append(result, matrix[row][left])
            }
            left++
        }
    }

    return result
}

Example Walkthrough

Given:

go

[
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]

Step-by-step result:

  • → 1 2 3
  • ↓ 6 9
  • ← 8 7
  • ↑ 4
  • → 5

Final output: [1 2 3 6 9 8 7 4 5]

Time and Space Complexity

MetricComplexityTime ComplexityO(m × n)Space ComplexityO(1) (excluding output)

Edge Cases

  • Single row or single column: Algorithm still works.
  • Empty matrix: Return empty array.
  • Non-square matrix: Handled due to flexible bounds.

Key Takeaways

  • Use four pointers (top, bottom, left, right) to track the layer boundaries.
  • Loop while top <= bottom and left <= right.
  • Elegant simulation technique without needing visited flags or direction arrays.



Comments

No comments yet

Add a new Comment

NUHMAN.COM

Information Technology website for Programming & Development, Web Design & UX/UI, Startups & Innovation, Gadgets & Consumer Tech, Cloud Computing & Enterprise Tech, Cybersecurity, Artificial Intelligence (AI) & Machine Learning (ML), Gaming Technology, Mobile Development, Tech News & Trends, Open Source & Linux, Data Science & Analytics

Categories

Tags

©{" "} Nuhmans.com . All Rights Reserved. Designed by{" "} HTML Codex