shlogg · Early preview
Rahul Kumar Barnwal @rahulgithub-web

Spiral Matrix Traversal In O(m*n) Time Complexity

Solve LeetCode 54: Spiral Matrix by defining boundaries (top, bottom, left, right) that shrink as you traverse the matrix in spiral order. Time complexity is O(m⋅n), space complexity is O(1).

Top Interview 150
The Spiral Matrix problem is a common challenge involving matrix traversal. Let’s break down LeetCode 54: Spiral Matrix and implement a solution that works for any m×n matrix.


  
  
  🚀 Problem Description

Given an m×n matrix, traverse it in spiral order and return the elements in a single array.


  
  
  💡 Examples

Example 1


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

    
    

    
    




Example 2


Input: matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]  
Output: [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]...