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!

Description

Constraints

  • Total elements in the matrix <= 100000
  • The values in the matrix ranges from -1000000000 and 1000000000
  • Expected time complexity : O(n*m) where n and m are the rows and columns respectively
  • Expected space complexity : O(1)
JAVASCRIPT
OUTPUT
Results will appear here.