Traverse a Matrix in Spiral Order (Hard)
Good evening! Here's our prompt for today.
You may see this problem at Intercom, Pivotal, Hudson River-trading, Zapier, Weave, Illumio, Intel, Akamai, Icims, and Nasdaq.
Given an m * n
matrix array, can you print all its elements in a spiral order as shown in the figure below? Try to use only O(1)
space!

Constraints
- Total elements in the matrix <=
100000
- The values in the matrix ranges from
-1000000000
and1000000000
- Expected time complexity :
O(n*m)
wheren
andm
are the rows and columns respectively - Expected space complexity :
O(1)
xxxxxxxxxx
58
var assert = require('assert');
function spiraltraverse(inmatrix) {
// fill this in
}
try {
assert.equal(
spiraltraverse([
[1, 2, 3, 4, 5, 6],
[7, 8, 9, 10, 11, 12],
]),
'1,2,3,4,5,6,12,11,10,9,8,7'
);
console.log(
'PASSED: `spiraltraverse([[1,2,3,4,5,6], [7,8,9,10,11,12]])` should return `1,2,3,4,5,6,12,11,10,9,8,7 `'
);
} catch (err) {
console.log(err);
}
try {
assert.equal(
spiraltraverse([
[1, 2, 3, 4],
[5, 6, 7, 8],
OUTPUT
Results will appear here.