Practice the most popular front-end questions asked in coding interviews with Frontend Churn

00:00:00

Given a 2D matrix of numbers, return a spiral traversal of the matrix in the clockwise direction.

```
matrix = [
[1, 2, 3, 4],
[12, 13, 14, 5],
[11, 16, 15, 6],
[10, 9, 8, 7],
];
```

```
[
1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12,
13, 14, 15, 16
]
```

In the clockwise direction, we go from

- Left to right (covering 1, 2, 3, 4)
- Top to bottom (covering 5, 6, 7).
- Right to left (covering 8, 9, 10).
- Bottom to top (covering 11, 12). And the cycle repeats until all the numbers are covered.

```
1 <= matrix.length <= 1000
1 <= matrix[i][j] <= 1000
```

Click to reveal

Try using indexes for `rows`

and `columns`

in the matrix. There can be 4 for-loops to iterate over rows and columns. How can you make sure that you cover all the elements?

Click to reveal

Is there a recursive approach to solve this problem? Can you try using recursion to print out the boundaries of the matrix and then step into a deeper level?

Uploaded by: Manu Arora

Share this problem on