All topics
141

Read a matrix along its diagonals

Tier 1Locked

Where it runs

1. The problem

You have a grid of numbers. You must write all its cells into one flat list, walking the grid along its diagonals. The direction alternates: you read one diagonal from bottom to top and the next one from top to bottom.

For [[1,2,3],[4,5,6],[7,8,9]] the answer is [1,2,4,7,5,3,6,8,9]. The whole task is walking this zig-zag correctly.

This step is part of the paid track

The first 33 steps are open to everyone: lesson, exercise and tests. This one opens with full access. Start with a free account and the free steps.

Create a free accountSee what is included

Recognise it

Matrix traversal (spiral / diagonal)

Say these words and it is this pattern

  • read or fill a grid in spiral order
  • walk a matrix diagonal by diagonal
  • rotate a matrix 90 degrees
  • visit every cell in a fixed geometric order

Looks similar, isn't

An r by c grid gives O(rc), because each cell is visited once. Space is O(1) beyond the output.

On LeetCode

Matrix problems that read or group cells along diagonals. Cells on one diagonal share the sum r + c, and on diagonals in the other direction they share the difference r minus c, so either number works as a key.

We use necessary cookies to run the site (sign-in and language). If you accept, we also load Google Analytics to see which pages are used, and Google reCAPTCHA to keep spam off the contact and bug-report forms. Privacy policy