Arrays and Hashing Walking a matrix

83. Spiral Matrix

Medium 147 DSA Sheet

You are given a matrix of integers matrix with m rows and n columns. Return all of its values in spiral order.

Spiral order starts at the top-left cell and moves right along the top row. At the end of the row it turns and goes down the right column, then left along the bottom row, then up the left column. It keeps turning clockwise in the same way, ring by ring toward the centre, until it has read every cell once.

Example 1

38-16074-592101

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

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

Explanation: The outer ring gives 3, 8, −1, 6 along the top, −5, 1 down the right, 10, 2, 9 back along the bottom and 0 up the left. Only the inner part of the middle row is left, so the spiral ends with 7 and 4.

Example 2

5-28

Input: matrix = [[5], [-2], [8]]

Output: [5,-2,8]

Explanation: With a single column, the spiral reads the top cell and then goes straight down. There is nothing to the left or the right to come back along.

Example 3

4-71093−10⁹610⁹

Input: matrix = [[4, -7, 1], [0, 9, 3], [-1000000000, 6, 1000000000]]

Output: [4,-7,1,3,1000000000,6,-1000000000,0,9]

Explanation: The outer ring holds eight values. The centre cell, 9, is a ring of its own and comes last.

Check your understanding

Work out the answer for this input before you write any code.

matrix = [[1, 2], [3, 4]]

Constraints

  • m == matrix.length, and every row has n values
  • 1 ≤ m, n and m × n ≤ 105
  • -109 ≤ matrix[i][j] ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.