Taro Logo

Spiral Matrix

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+36
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
3.3K views
Topics:
Arrays

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

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]

Constraints:

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

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What should be returned if the input matrix is empty or null?
  2. Can the matrix be non-square (i.e., $m \neq n$), such as a single row or a single column?
  3. What is the expected data type and value range of the integers within the matrix?
  4. Should the traversal strictly start at the top-left corner and always proceed in a clockwise direction?
  5. Is the original matrix allowed to be modified during the traversal, or should it remain untouched?

Brute Force Solution

Approach

Imagine you are tasked with collecting every single item from a grid by walking around its outer edges and gradually moving inward. The brute force approach exhaustively traces the entire path by systematically visiting every location on the grid one by one, following a strict set of directional rules until no unvisited locations remain.

Here's how the algorithm would work step-by-step:

  1. Start at the top-left corner of the grid and begin walking to the right.
  2. Continue walking straight in your current direction until you reach the edge of the grid or a spot you have already visited.
  3. When you can no longer go straight, make a ninety-degree turn in a clockwise direction.
  4. Record the item you are currently standing on as part of your collection.
  5. Repeat the process of walking, turning when blocked, and recording items until every single spot in the grid has been visited and collected.

Code Implementation

def spiralOrder(matrix):
    if not matrix:
        return []

    row_count = len(matrix)
    column_count = len(matrix[0])
    total_elements = row_count * column_count
    visited_matrix = [[False for _ in range(column_count)] for _ in range(row_count)]
    result_collection = []
    
    row_index = 0
    column_index = 0
    current_direction = 0
    row_directions = [0, 1, 0, -1]
    column_directions = [1, 0, -1, 0]

    # Traverse step-by-step, turning clockwise only when hitting boundaries or visited cells
    for step_counter in range(total_elements):
        result_collection.append(matrix[row_index][column_index])
        visited_matrix[row_index][column_index] = True

        next_row = row_index + row_directions[current_direction]
        next_column = column_index + column_directions[current_direction]

        if (0 <= next_row < row_count) and (0 <= next_column < column_count) and not visited_matrix[next_row][next_column]:
            row_index = next_row
            column_index = next_column
        else:
            current_direction = (current_direction + 1) % 4
            row_index += row_directions[current_direction]
            column_index += column_directions[current_direction]

    # Return the fully collected spiral sequence once all grid locations are processed
    return result_collection

Big(O) Analysis

Time Complexity
O(m * n) – In this simulation approach, the algorithm visits every single cell in the grid exactly once as it spirals inward from the edges. For a grid with m rows and n columns, the total number of processed cells is directly driven by the total dimensions of the matrix. This exhaustive traversal results in m times n operations to collect all the values. Therefore, the total operations approximate the product of the grid dimensions, which simplifies to the Big O time complexity of O(m * n) or O(n²) for a square matrix.
Space Complexity
O(N) – To satisfy the requirement of collecting and returning every item from the grid, we allocate a single result list to store the visited elements. As the algorithm traverses the grid, this dynamic list grows proportionally to hold all N total elements. Beyond this output collection, the algorithm only utilizes a few primitive integer variables to track the four boundary pointers and directional state. Therefore, the auxiliary space complexity is driven entirely by the output list, scaling linearly with the total number of elements N.

Optimal Solution

Approach

The optimal approach to solving this puzzle is to peel away the grid like the layers of an onion, moving strictly along the outer edges in a continuous clockwise loop. By shrinking the active boundaries inward after completing each full circuit, we visit every single spot exactly once without missing a corner or overlapping.

Here's how the algorithm would work step-by-step:

  1. Imagine standing at the top-left corner of the grid and looking toward the right.
  2. Walk all the way along the topmost edge until you reach the far-right corner, noting down everything you pass.
  3. Once at the far right, turn downward and walk straight down along the rightmost edge to the bottom-right corner.
  4. From the bottom-right, turn left and walk backward along the bottom edge until you reach the bottom-left corner.
  5. From the bottom-left, turn upward and walk straight up along the leftmost edge until you are just below your starting point.
  6. Now that the outer frame is fully explored, shrink your working area inward by one step on all four sides.
  7. Repeat this exact walking sequence of right, down, left, and up within the newly shrunk boundaries.
  8. Keep shrinking the boundaries and walking the perimeter until the entire grid has been completely uncovered.

Code Implementation

def spiral_order(matrix_grid):
    if not matrix_grid:
        return []

    result_collection = []
    top_boundary = 0
    bottom_boundary = len(matrix_grid) - 1
    left_boundary = 0
    right_boundary = len(matrix_grid[0]) - 1

    # We peel the matrix layer by layer until boundaries cross, ensuring all elements are visited.
    while top_boundary <= bottom_boundary and left_boundary <= right_boundary:

        for column_index in range(left_boundary, right_boundary + 1):
            result_collection.append(matrix_grid[top_boundary][column_index])
        top_boundary += 1

        for row_index in range(top_boundary, bottom_boundary + 1):
            result_collection.append(matrix_grid[row_index][right_boundary])
        right_boundary -= 1

        # Checking boundaries prevents duplicate processing of rows or columns in non-square matrices.
        if top_boundary <= bottom_boundary:
            for column_index in range(right_boundary, left_boundary - 1, -1):
                result_collection.append(matrix_grid[bottom_boundary][column_index])
            bottom_boundary -= 1

        # Checking boundaries prevents duplicate processing of rows or columns in non-square matrices.
        if left_boundary <= right_boundary:
            for row_index in range(bottom_boundary, top_boundary - 1, -1):
                result_collection.append(matrix_grid[row_index][left_boundary])
            left_boundary += 1

    return result_collection

Big(O) Analysis

Time Complexity
O(m * n) – In this onion-peeling approach, every single element in the m by n grid is visited exactly once as we traverse the outer layers inward. The total number of operations is directly driven by the total number of cells, meaning we perform a constant amount of work for each element. This results in m * n operations in total, which simplifies to the Big O time complexity of O(m * n), or O(n^2) for a square matrix.
Space Complexity
O(N) – To satisfy the requirements of the problem, we must allocate an auxiliary output list that stores all elements of the matrix, where N represents the total number of elements in the grid. The algorithm only utilizes a few primitive pointer variables to track the four active boundaries, which require constant extra memory. Therefore, the dominant factor determining the extra memory usage is the output list scaling linearly with the total number of elements N. Ultimately, the auxiliary space complexity simplifies to Big O of N.

Edge Cases

Empty matrix or null input where rows or columns equal zero
How to Handle:
Check for empty input upfront and return an empty list immediately to prevent out-of-bounds errors.
Single row matrix of dimensions 1 x n
How to Handle:
The outer loop runs once, and the right-to-left and bottom-to-top traversal steps are skipped by boundary checks.
Single column matrix of dimensions m x 1
How to Handle:
The traversal correctly processes the single column downwards while horizontal loops are safely bypassed.
A 1 x 1 matrix containing just a single element
How to Handle:
The algorithm appends the single element and terminates without triggering any out-of-bounds boundary violations.
Extremely large matrices near memory limits
How to Handle:
The O(m * n) time and O(1) auxiliary space approach prevents memory overflow by avoiding recursion.
Matrices containing negative numbers, zeros, and extreme boundary values
How to Handle:
Since the algorithm only reads values and checks coordinate bounds, value magnitudes do not affect traversal.
Non-square rectangular matrices where rows and columns differ significantly
How to Handle:
Using four distinct boundary pointers ensures correct inward shrinkage regardless of aspect ratio.
Boundary cross-over during the final inner layer traversal
How to Handle:
Strict conditional checks inside the loops prevent duplicate element insertions when rows or columns collapse.
0/75 completed