Close Menu
    Code and Debug
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook X (Twitter) Instagram YouTube WhatsApp
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook Instagram YouTube LinkedIn WhatsApp
    Code and Debug – BlogCode and Debug – Blog
    Code and Debug – BlogCode and Debug – Blog
    Home»Data Structures & Algorithms»Spiral Matrix | Leetcode 54 | Explained in Python
    Data Structures & Algorithms

    Spiral Matrix | Leetcode 54 | Explained in Python

    codeanddebugBy codeanddebug29 June 2025No Comments3 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Featured image of question to print the matrix in spiral manner
    Share
    Facebook Twitter LinkedIn Pinterest Email

    LeetCode “Spiral Matrix” (#54) asks you to return all the elements of an m × n matrix in clock-wise spiral order, starting from the top-left corner.

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

    Think of tracing the outer frame of the matrix, then peeling it away layer by layer—just like unwrapping an onion.

    Here’s the [Problem Link] to begin with.

    Contents:
     [show]
    • Optimal Solution (Pointer Shrinking Technique)
      • Intuition and Approach
      • Code Implementation
      • Code Explanation
      • Dry Run (3 × 3 Matrix)
      • Time and Space Complexity
      • Conclusion

    Optimal Solution (Pointer Shrinking Technique)

    Intuition and Approach

    1. Four Pointers mark the current “unvisited rectangle”:
      top row, bottom row, left column, right column.
    2. Repeatedly walk the perimeter of that rectangle in four mini-passes:
      1. Left ➜ Right across the top row.
      2. Top ➜ Bottom down the right column.
      3. Right ➜ Left across the bottom row (if any rows remain).
      4. Bottom ➜ Top up the left column (if any cols remain).
    3. After completing the loop, shrink the rectangle:
      increment top, decrement bottom, increment left, decrement right.
    4. Stop when top > bottom or left > right.

    Because every element is touched exactly once and we reuse the result list for output, the algorithm runs in O(m·n) time with O(1) extra space.

    Code Implementation

    class Solution:
        def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
            # Handle empty input
            if not matrix or not matrix[0]:
                return []
    
            result = []                           # stores the spiral order
    
            # Initialize boundary pointers
            top, left = 0, 0
            bottom, right = len(matrix) - 1, len(matrix[0]) - 1
    
            # Continue until the boundaries cross
            while top <= bottom and left <= right:
                # Traverse the top row from left to right
                for i in range(left, right + 1):
                    result.append(matrix[top][i])
                top += 1                          # top row is done
    
                # Traverse the right column from top to bottom
                for i in range(top, bottom + 1):
                    result.append(matrix[i][right])
                right -= 1                        # right column is done
    
                # Traverse the bottom row from right to left (if any)
                if top <= bottom:
                    for i in range(right, left - 1, -1):
                        result.append(matrix[bottom][i])
                    bottom -= 1                   # bottom row is done
    
                # Traverse the left column from bottom to top (if any)
                if left <= right:
                    for i in range(bottom, top - 1, -1):
                        result.append(matrix[i][left])
                    left += 1                     # left column is done
    
            return result

    Code Explanation

    • Boundaries: top, bottom, left, and right fence in the part of the matrix we still need to visit.
    • Perimeter Walk: Each loop iteration captures one “ring” of the onion in four straight passes.
    • Boundary Update: After finishing a side, we move the corresponding pointer inward so we don’t revisit those cells.
    • Termination: When the pointers cross, no unvisited cells remain.

    Dry Run (3 × 3 Matrix)

    SteptopbottomleftrightElements Addedresult after step
    102021 2 3 (top row)1 2 3
    212026 9 (right column)1 2 3 6 9
    312018 7 (bottom row)1 2 3 6 9 8 7
    411014 (left column)1 2 3 6 9 8 7 4
    511115 (final center element)1 2 3 6 9 8 7 4 5

    Pointers cross, done!

    Time and Space Complexity

    • Time: O(m × n) – every cell is visited exactly once.
    • Space: O(1) extra – aside from the output list, only four integer pointers are used.

    Conclusion

    Using four shrinking boundaries lets us capture the Spiral Matrix order cleanly, without auxiliary grids or markers. This pattern—peel the outer layer, shrink, repeat—is a handy template for many 2-D traversal problems.

    Join our Advance DSA COURSE

    For any changes to the article, kindly email at code@codeanddebug.in or contact us at +91-9712928220.

    2D Array Hard
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleRotate Image | Leetcode 48 | Explained with Images
    Next Article 3Sum | Leetcode 15 | Explained in Python
    codeanddebug
    • Website

    Related Posts

    Data Structures & Algorithms

    Find First and Last Position of Element in Sorted Array | Leetcode 34 | Optimal Binary Search

    2 July 2025
    Data Structures & Algorithms

    Ceil The Floor | Binary Search Implementation

    2 July 2025
    Data Structures & Algorithms

    Search Insert Position | Leetcode 35 | Explained in Python

    2 July 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Categories
    • Data Structures & Algorithms (91)
      • Beginner (42)
      • Expert (22)
      • Intermediate (27)
    • Uncategorised (1)
    Recent Posts

    Find First and Last Position of Element in Sorted Array | Leetcode 34 | Optimal Binary Search

    2 July 2025

    Ceil The Floor | Binary Search Implementation

    2 July 2025

    Search Insert Position | Leetcode 35 | Explained in Python

    2 July 2025

    Implement Upper Bound

    2 July 2025

    Implement Lower Bound | Floor in a Sorted Array (GFG)

    2 July 2025
    Facebook Instagram YouTube LinkedIn WhatsApp
    © 2025 Code and Debug. All rights reserved.

    Type above and press Enter to search. Press Esc to cancel.