spiralMatrix

Medium · Array Manipulations · 1 test cases

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

Examples

spiralMatrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) → [1, 2, 3, 6, 9, 8, 7, 4, 5]

Starter code

function spiralMatrix(matrix) {

}

Complexity of the optimal solution

Time O(n), space O(n). Let n be the total number of elements (m * n). The algorithm visits each element of the matrix exactly once while peeling off the outer layers. The array operations inside the loop (`shift`, `pop`, `map`) process the remaining elements. Overall time complexity is O(n), and space is O(n) for the result array.

Solve spiralMatrix in the browser