Print the matrix in spiral manner

Arrays FAQs(Medium) Medium

Given an M * N matrix, print the elements in a clockwise spiral manner. Return an array with the elements in the order of their appearance when printed in a spiral manner.

Examples:

Input: matrix = [[1, 2, 3], [4 ,5 ,6], [7, 8, 9]]

Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]

Explanation: The elements in the spiral order are 1, 2, 3 -> 6, 9 -> 8, 7 -> 4, 5

Input: matrix = [[1, 2, 3, 4], [5, 6, 7, 8]]

Output: [1, 2, 3, 4, 8, 7, 6, 5]

Explanation: The elements in the spiral order are 1, 2, 3, 4 -> 8, 7, 6, 5

Input: matrix = [[1, 2], [3, 4], [5, 6], [7, 8]]

Constraints

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 100
  • -100 <= matrix[i][j] <= 100

Hints

  • Treat the matrix as a collection of concentric rectangular layers. Traverse each layer in four steps: top row (left to right), right column (top to bottom), bottom row (right to left), and left column (bottom to top).
  • Maintain four boundaries (top, bottom, left, right) to keep track of the limits of the matrix as you spiral inward.

Company Tags

Visa Reddit Twilio Square Nutanix Flipkart Target AMD American Express Alibaba Unity Technologies Activision Blizzard Bain & Company Medtronic Goldman Sachs Splunk Bloomberg Dropbox PwC Philips Healthcare Oracle Ubisoft Uber JPMorgan Chase IBM TCS Cognizant Accenture Infosys Capgemini Wipro