Spiral Matrix

Traversing a Matrix in Spiral Order

Traversing a matrix in spiral order is a common problem in programming, where the goal is to extract all elements of a matrix following a specific pattern.

The traversal begins at the top-left corner and proceeds in a clockwise spiral until all elements are covered.

Pair with given sum - Two Sum

Problem Statement

You are given a rectangular matrix of integers with dimensions m×nm \times n. The task is to return a list containing all the elements of the matrix arranged in spiral order.

This means traversing the matrix in a clockwise spiral pattern, starting from the top-left corner.

Constraints:

  • 1 <= matrix.length, matrix[i].length <= 10
  • -100 <= matrix[i][j] <= 100
Sprial Matrix 2

There are mainly 3 approach to solve this problem – 

  1. Recursion
  2. Iteration
  3. Iteration (Optimal)

1. Recursion

  • Time complexity: O(m∗n)
  • Space complexity: O(min(m,n))

Where m is the number of rows and n is the number of columns.

2. Iteration

Time & Space Complexity
    • Time complexity: O(m∗n)
    • Space complexity: O(1)

Where m is the number of rows and n is the number of columns.

Code

3. Iteration (Optimal)

  • Time complexity: O(m∗n)
  • Space complexity: O(1)

Where m is the number of rows and n is the number of columns.

Code

More Articles