Bird
Raised Fist0
Interview PrepmatricesmediumAmazonGoogleFacebook

Diagonal Traverse

Choose your preparation mode4 modes available
</>
IDE
def findDiagonalOrder(mat: list[list[int]]) -> list[int]:public int[] findDiagonalOrder(int[][] mat)vector<int> findDiagonalOrder(vector<vector<int>>& mat)function findDiagonalOrder(mat)
def findDiagonalOrder(mat):
    # Write your solution here
    pass
class Solution {
    public int[] findDiagonalOrder(int[][] mat) {
        // Write your solution here
        return new int[0];
    }
}
#include <vector>
using namespace std;

vector<int> findDiagonalOrder(vector<vector<int>>& mat) {
    // Write your solution here
    return {};
}
function findDiagonalOrder(mat) {
    // Write your solution here
}
Coming soon
0/10
Common Bugs to Avoid
Wrong: [1,4,2,3,5,6,7,8,9]Not toggling direction after each diagonal, causing incorrect traversal order.✅ Toggle direction after processing each diagonal and reverse intermediate list on even diagonals.
Wrong: [1,2,3,4,5]Failing on single column or single row matrices by reversing single element diagonals incorrectly.✅ Do not reverse intermediate list if it contains only one element.
Wrong: IndexError or crash on empty inputNo check for empty matrix or empty first row before traversal.✅ Add guard clause: if not mat or not mat[0]: return [].
Wrong: [1,2,5,3,4,6]Incorrect start indices for diagonals when diagonal index >= number of columns.✅ For diagonal d >= n, start row = d - n + 1, start col = n - 1.
Wrong: TLE or timeout on large inputUsing exponential or nested loops simulating each diagonal inefficiently.✅ Implement O(m*n) traversal using direction flags and index updates without nested loops over diagonals.
✓
Test Cases
t1_01basic
Input{"mat":[[1,2,3],[4,5,6],[7,8,9]]}
Expected[1,2,4,7,5,3,6,8,9]

Traverse diagonally starting at (0,0): 1 → up-right to 2 → down-left to 4 → down-left to 7 → up-right to 5 → up-right to 3 → down-left to 6 → down-left to 8 → up-right to 9

t1_02basic
Input{"mat":[[1,2,3,4],[5,6,7,8],[9,10,11,12]]}
Expected[1,2,5,9,6,3,4,7,10,11,8,12]

Traverse diagonally: 1 → up-right to 2 → down-left to 5 → down-left to 9 → up-right to 6 → up-right to 3 → down-left to 4 → down-left to 7 → up-right to 10 → up-right to 11 → down-left to 8 → up-right to 12

t2_01edge
Input{"mat":[]}
Expected[]

Empty matrix input should return empty output list.

t2_02edge
Input{"mat":[[42]]}
Expected[42]

Single element matrix returns that element as the only output.

t2_03edge
Input{"mat":[[1,2,3,4,5]]}
Expected[1,2,3,4,5]

Single row matrix returns elements in row order as diagonal traversal is linear.

t2_04edge
Input{"mat":[[1],[2],[3],[4],[5]]}
Expected[1,2,3,4,5]

Single column matrix returns elements in column order as diagonal traversal is linear.

t3_01corner
Input{"mat":[[1,2],[3,4],[5,6]]}
Expected[1,2,3,5,4,6]

Rectangular matrix with more rows than columns; correct zigzag traversal.

t3_02corner
Input{"mat":[[1,2,3],[4,5,6]]}
Expected[1,2,4,5,3,6]

Rectangular matrix with more columns than rows; correct zigzag traversal.

t3_03corner
Input{"mat":[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]}
Expected[1,2,4,7,5,3,6,8,10,11,9,12]

Greedy trap test: ensure direction flips after each diagonal rather than trying to traverse greedily in one direction.

t4_01performance
Input{"mat":[[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99],[100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199],[200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299],[300,301,302,303,304,305,306,307,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,378,379,380,381,382,383,384,385,386,387,388,389,390,391,392,393,394,395,396,397,398,399],[400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426,427,428,429,430,431,432,433,434,435,436,437,438,439,440,441,442,443,444,445,446,447,448,449,450,451,452,453,454,455,456,457,458,459,460,461,462,463,464,465,466,467,468,469,470,471,472,473,474,475,476,477,478,479,480,481,482,483,484,485,486,487,488,489,490,491,492,493,494,495,496,497,498,499],[500,501,502,503,504,505,506,507,508,509,510,511,512,513,514,515,516,517,518,519,520,521,522,523,524,525,526,527,528,529,530,531,532,533,534,535,536,537,538,539,540,541,542,543,544,545,546,547,548,549,550,551,552,553,554,555,556,557,558,559,560,561,562,563,564,565,566,567,568,569,570,571,572,573,574,575,576,577,578,579,580,581,582,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599],[600,601,602,603,604,605,606,607,608,609,610,611,612,613,614,615,616,617,618,619,620,621,622,623,624,625,626,627,628,629,630,631,632,633,634,635,636,637,638,639,640,641,642,643,644,645,646,647,648,649,650,651,652,653,654,655,656,657,658,659,660,661,662,663,664,665,666,667,668,669,670,671,672,673,674,675,676,677,678,679,680,681,682,683,684,685,686,687,688,689,690,691,692,693,694,695,696,697,698,699],[700,701,702,703,704,705,706,707,708,709,710,711,712,713,714,715,716,717,718,719,720,721,722,723,724,725,726,727,728,729,730,731,732,733,734,735,736,737,738,739,740,741,742,743,744,745,746,747,748,749,750,751,752,753,754,755,756,757,758,759,760,761,762,763,764,765,766,767,768,769,770,771,772,773,774,775,776,777,778,779,780,781,782,783,784,785,786,787,788,789,790,791,792,793,794,795,796,797,798,799],[800,801,802,803,804,805,806,807,808,809,810,811,812,813,814,815,816,817,818,819,820,821,822,823,824,825,826,827,828,829,830,831,832,833,834,835,836,837,838,839,840,841,842,843,844,845,846,847,848,849,850,851,852,853,854,855,856,857,858,859,860,861,862,863,864,865,866,867,868,869,870,871,872,873,874,875,876,877,878,879,880,881,882,883,884,885,886,887,888,889,890,891,892,893,894,895,896,897,898,899],[900,901,902,903,904,905,906,907,908,909,910,911,912,913,914,915,916,917,918,919,920,921,922,923,924,925,926,927,928,929,930,931,932,933,934,935,936,937,938,939,940,941,942,943,944,945,946,947,948,949,950,951,952,953,954,955,956,957,958,959,960,961,962,963,964,965,966,967,968,969,970,971,972,973,974,975,976,977,978,979,980,981,982,983,984,985,986,987,988,989,990,991,992,993,994,995,996,997,998,999]]}
⏱ Performance - must finish in 2000ms

Large 100x100 matrix (10,000 elements) to test O(m*n) time complexity within 2 seconds.

Practice

(1/5)
1. Consider the following code snippet that rotates a 3x3 matrix by 90 degrees clockwise in-place. After the first iteration of the outer loop (layer = 0) and the first iteration of the inner loop (i = 0), what is the value of matrix[0][2]?
easy
A. 7
B. 1
C. 3
D. 9

Solution

  1. Step 1: Trace first iteration (layer=0, i=0)

    first=0, last=2, offset=0; top=matrix[0][0]=1
  2. Step 2: Perform swaps

    matrix[0][0] = matrix[2][0] = 7; matrix[2][0] = matrix[2][2] = 9; matrix[2][2] = matrix[0][2] = 3; matrix[0][2] = top = 1
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    matrix[0][2] updated to 7 after first swap [OK]
Hint: Track swaps carefully to find updated element values [OK]
Common Mistakes:
  • Confusing indices during swaps
  • Mixing up top and offset calculations
2. You are given a square matrix and asked to transform it so that rows become columns and columns become rows without using extra space. Which approach guarantees an optimal in-place solution?
easy
A. Use a brute force approach by creating a new matrix and copying elements accordingly.
B. Swap elements symmetrically across the diagonal only once, iterating over the upper triangle of the matrix.
C. Apply a greedy approach by swapping elements row-wise without considering the diagonal symmetry.
D. Use dynamic programming to store intermediate transposed states and build the final matrix.

Solution

  1. Step 1: Understand the problem constraints

    The problem requires an in-place transpose of a square matrix, meaning no extra matrix can be used.
  2. Step 2: Identify the correct approach

    Swapping elements symmetrically across the diagonal once (upper triangle only) ensures each pair is swapped exactly once, achieving in-place transpose efficiently.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Swapping only upper triangle elements avoids double swaps and extra space [OK]
Hint: Swap only upper triangle elements once [OK]
Common Mistakes:
  • Using extra space unnecessarily
  • Swapping elements twice by iterating entire matrix
  • Ignoring diagonal symmetry leading to incorrect results
3. Identify the bug in the following in-place Game of Life code snippet that causes incorrect neighbor counts and final states.
medium
A. Line checking neighbors lacks boundary condition checks causing index errors
B. Final loop does not convert encoded states back to original states
C. Neighbor counting incorrectly includes dead cells as live
D. Encoding uses wrong integers for state transitions

Solution

  1. Step 1: Examine neighbor counting loop

    The code checks board[x][y] without verifying if x,y are within valid indices, risking index errors or invalid counts.
  2. Step 2: Confirm other parts are correct

    Final decoding loop correctly converts 2->0 and 3->1; encoding uses correct integers; neighbor counting excludes dead cells properly.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Missing boundary check causes incorrect neighbor counts or runtime errors [OK]
Hint: Always check boundaries before accessing neighbors [OK]
Common Mistakes:
  • Forgetting boundary checks in neighbor loops
  • Not finalizing encoded states after first pass
  • Misusing encoding integers
4. Identify the bug in the following code snippet for finding lucky numbers in a matrix:
from typing import List

def luckyNumbers(matrix: List[List[int]]) -> List[int]:
    m, n = len(matrix), len(matrix[0])
    row_mins = [min(row) for row in matrix]
    col_maxs = [min(matrix[i][j] for i in range(m)) for j in range(n)]  # Bug here
    return [matrix[i][j] for i in range(m) for j in range(n) if matrix[i][j] == row_mins[i] == col_maxs[j]]
What is the bug?
medium
A. Using min instead of max when computing column maximums.
B. Using min for row minimums instead of max.
C. Incorrectly iterating over rows and columns in the list comprehension for the result.
D. Not handling empty matrix input before processing.

Solution

  1. Step 1: Analyze column maximum computation

    The code uses min(matrix[i][j] for i in range(m)) to compute col_maxs, which is incorrect because it finds the minimum instead of the maximum.
  2. Step 2: Understand impact

    Using min instead of max causes the algorithm to identify incorrect elements as lucky numbers or miss valid ones.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Column maxs must use max(), not min() [OK]
Hint: Check min vs max carefully in column computations [OK]
Common Mistakes:
  • Confusing min and max in column computations
  • Ignoring empty matrix edge cases
  • Misindexing in list comprehensions
5. Consider this buggy version of the optimal Set Matrix Zeroes code. Which line contains the subtle bug that causes incorrect zeroing in some cases?
def setZeroes(matrix):
    m, n = len(matrix), len(matrix[0])
    first_row_zero = any(matrix[0][j] == 0 for j in range(n))
    first_col_zero = any(matrix[i][0] == 0 for i in range(m))
    for i in range(m):  # Bug here: starts from 0 instead of 1
        for j in range(n):
            if matrix[i][j] == 0:
                matrix[i][0] = 0
                matrix[0][j] = 0
    for i in range(1, m):
        for j in range(1, n):
            if matrix[i][0] == 0 or matrix[0][j] == 0:
                matrix[i][j] = 0
    if first_row_zero:
        for j in range(n):
            matrix[0][j] = 0
    if first_col_zero:
        for i in range(m):
            matrix[i][0] = 0
medium
A. Line with 'for i in range(m):' (marking zeros in first pass)
B. Line with 'first_row_zero = any(matrix[0][j] == 0 for j in range(n))'
C. Line with 'first_col_zero = any(matrix[i][0] == 0 for i in range(m))'
D. Line with 'for i in range(1, m):' (zeroing based on flags)

Solution

  1. Step 1: Identify marking loop range

    The marking loop should start from 1 to avoid overwriting first row/column flags prematurely.
  2. Step 2: Understand impact

    Starting from 0 causes first row/column to be overwritten before flags are saved, losing zero info.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Changing loop to start at 1 fixes the bug [OK]
Hint: Mark zeros starting from index 1 to preserve flags [OK]
Common Mistakes:
  • Zeroing first row/column too early
  • Incorrect loop ranges causing info loss
  • Confusing first pass marking with zeroing pass
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard