Skip to the code
+25 XP

#79 Zigzag Diagonal Reading

medium

An image encoder reads pixel blocks along diagonals in a zigzag. Diagonal d holds the cells with r + c === d. Diagonals are read in order d = 0, 1, 2, .... Even diagonals are read going up and to the right (row decreasing); odd diagonals are read going down and to the left (row increasing).

Write zigzagRead(grid) that returns the values of grid in that order.

Example 1

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

Diagonal 1 goes down (2, 5), diagonal 2 goes up (6, 3), diagonal 3 goes down (4, 7).

Example 2

Input: grid = [[1],[2],[3]]
Output: [1,2,3]

Each diagonal of a single column holds one cell.

Constraints

  • 1 <= rows, cols <= 10^5
  • rows * cols <= 10^6
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).