Medium · Direction Simulation
Understand → Visualise → Practice.
Return rectangular matrix values by alternating up-right and down-left diagonals.
Every cell on the same anti-diagonal has the same r + c. Collect the diagonals, then read even-numbered ones upwards and odd ones downwards.
For each cell, append its value to the list for diagonal r + c, scanning rows top to bottom.
Diagonal 0, 2, 4… go up-right, so reverse them; odd diagonals go down-left and stay in order.
Append the diagonals in order 0, 1, 2, ….
O(rows × cols) time and O(rows × cols) space.
Simulating moves directly is easy to get wrong at the edges; grouping by r + c avoids edge cases.
Read the full guide first: Matrices and 2-D Arrays.
Guest mode lets you understand, visualise and run the sample tests. Create a free account to submit and save your solutions.