Problem 319859 · medium · Phase 03 Linear Management & Searching

Zigzag Along the Anti-Diagonals

matrix · traversal · index arithmetic

Given an m x n grid matrix, return all of its elements in zigzag anti-diagonal order: walk the anti-diagonals (cells with the same row + col) starting at the top-left cell, going up-right on the first diagonal, then down-left on the next, alternating.

Examples

Input:  matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output: [1, 2, 4, 7, 5, 3, 6, 8, 9]
Explanation: diagonals are [1], [2, 4], [7, 5, 3], [6, 8], [9] - the second is read
             downwards, the third upwards, and so on.

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

Constraints

  • 1 <= m, n <= 500
  • Target: O(m * n) time.

Goals

  • Group cells by the sum of their row and column indices
  • Alternate the direction of traversal on consecutive diagonals
  • Handle rectangular grids where diagonals are cut off by the borders
Starting Python…