Given a matrix of m x n elements, return the elements in spiral order.
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
Output: [1,2,3,6,9,8,7,4,5]
This problem is quite popular and is frequently asked during interviews.
Solution: To traverse the matrix in spiral order, we have to go along the boundaries starting from the top left element at i = 0, j = 0 where i, j represent the row and column indexes respectively. Let’s view the matrix as a collection of layers. Once we complete the outermost layer, we have to keep traversing the inner layers until no element is left to be visited. We can think of this as traversing multiple matrices in spiral order layer by layer.

What are some things to remember while traversing?
- We need some indexes to track our traversal. A straightforward approach is to have four indexes to keep track of the four boundaries of the matrix. These will be called left, right, top and bottom.
- We will be using a while loop to add elements to a results array as long as
left < right and top < bottom. This indicates that there are still elements left to traverse. - Inside the while loop, we will be using four for loops to traverse each boundary.
- Avoid adding duplicate elements when changing directions ie., once we finish traversing a row [1, 2, 3, 4, 5], we have to increment the row index to avoid adding 5 again during the right most column traversal. Similarly, right and bottom pointers should be decremented upon completing their respective boundary traversals.
- This problem code is nothing fancy but a matter of writing clear code without getting confused with the indices. The best way to get it right is to write the for loops as you traverse an example asymmetric matrix. This is because, a symmetric matrices usually do not help us handle edge cases in matrix problems.
- One corner case for this problem is when we are traversing a column matrix as shown below where m = 4, n = 1.

In this case, we first initialize these variables.
top = 0
bottom = m #4
left = 0
right = n #1
Top boundary: row = top = 0, col = left to right [0, 1). Results = [1]. Increment top pointer, top = 1.
Right boundary: row = top to bottom [1, 4), col = right – 1 = 0. Results = [ 1, 2, 3, 4]. Decrement right pointer, right = 0.
Now after the above two for loops, we are done traversing the entire matrix. But the next traversal will add duplicate elements to the results.
Bottom boundary: row = bottom – 1 = 3, col = right – 1 to left – 1 [0, -1). Results = [1, 2, 3, 4, 4]
This will attempt to traverse the bottom element 4 again. So right after traversing top and right boundaries, we have to always check whether left < right and top < bottom condition still holds true. In this case top < bottom since 1 < 4 but left = right since 0 = 0 indicating that we are about to traverse a boundary again.
Time Complexity: We will end up visiting each element of the matrix, so time complexity will be O(M * N).
Space Complexity: Constant variables are used to track boundaries, so no additional space is being used. The space complexity will be O(1).
Code:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix or not matrix[0]:
return []
m, n = len(matrix), len(matrix[0])
top, bottom = 0, m
left, right = 0, n
results = []
while top < bottom and left < right:
# traverse top boundary
for i in range(left, right):
results.append(matrix[top][i])
top += 1
# traverse right boundary
for i in range(top, bottom):
results.append(matrix[i][right-1])
right -= 1
if top < bottom and left < right:
# traverse bottom boundary
for i in range(right - 1, left - 1, -1):
results.append(matrix[bottom-1][i])
bottom -= 1
# traverse left boundary
for i in range(bottom - 1, top - 1, -1):
results.append(matrix[i][left])
left += 1
return results
Testing: The following cases are good to test for matrix problems.
- Empty matrix: []
- Empty rows: [[]]
- Single value matrix: [[1]]
- Two element matrix: [[1, 2]]
- Column matrix: [[1,2,3,4]]
- Row matrix: [[1],[2],[3],[4]]
- Symmetric matrix: [[1,2,3, 4],[4,5,6, 8], [9,10,11,12],[13,14,15,16]]
- Asymmetric matrix: [[1,2,3, 4],[4,5,6, 8]]
Want to try solving this problem? https://leetcode.com/problems/spiral-matrix/
Hope you enjoyed this post on traversing a matrix in spiral order. Have a great day!




