← Nagarro questions

Print given matrix in a spiral form

Filed under Nagarro

Free read 3 of 3

Initialize four variables: top, bottom, left, and right to represent the current edges of the matrix.

The question

Given an m x n matrix, return all elements of the matrix in a clockwise spiral order starting from the top-left corner.

Constraints

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

Examples

Input
matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output
[1,2,3,6,9,8,7,4,5]
Why
The spiral path is: Right (1,2,3), Down (6,9), Left (8,7), Up (4), Right (5).

Approach

  1. Initialize four variables: top, bottom, left, and right to represent the current edges of the matrix.

Solution

O(M*N) time, O(1) space

Python
class Solution:
    def spiralOrder(self, matrix):
        if not matrix: return []
        res = []
        t, b = 0, len(matrix) - 1
        l, r = 0, len(matrix[0]) - 1
        while t <= b and l <= r:
            for i in range(l, r + 1): res.append(matrix[t][i])
            t += 1
            for i in range(t, b + 1): res.append(matrix[i][r])
            r -= 1
            if t <= b:
                for i in range(r, l - 1, -1): res.append(matrix[b][i])
                b -= 1
            if l <= r:
                for i in range(b, t - 1, -1): res.append(matrix[i][l])
                l += 1
        return res

Tips

  • What they are testing: Tests your ability to manage complex boundary conditions and state transitions without errors.
  • Common mistake: Forgetting to re-check boundary conditions (like top <= bottom) after the first two movements inside the loop, causing duplicate processing.

Related Nagarro questions

Collected from public candidate posts and coding forums. Updated Nov 2026.