Bird
Raised Fist0
Interview PrepmatricesmediumAmazonGoogleFacebook

Diagonal Traverse

Choose your preparation mode4 modes available
🎯
Diagonal Traverse
mediumMATRIXAmazonGoogleFacebook

Imagine you have a spreadsheet and want to read its cells diagonally instead of row-wise or column-wise, like reading a zigzag pattern across the sheet.

💡 This problem requires traversing a matrix in a diagonal zigzag pattern, which is not straightforward because the direction changes after each diagonal. Beginners often struggle to keep track of indices and direction changes simultaneously.
📋
Problem Statement

Given an m x n matrix, return all elements of the matrix in a diagonal order starting from the top-left element. The traversal moves diagonally up-right and down-left alternately until all elements are visited.

1 ≤ m, n ≤ 10^4Total elements m * n ≤ 10^5
💡
Example
Input"[[1,2,3],[4,5,6],[7,8,9]]"
Output[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

  • Single element matrix → output is that element
  • Single row matrix → output is the row itself
  • Single column matrix → output is the column itself
  • Rectangular matrix with more rows than columns → correct zigzag traversal
  • Rectangular matrix with more columns than rows → correct zigzag traversal
⚠️
Common Mistakes
Forgetting to flip direction at boundaries

Traversal goes out of bounds or repeats elements

✅ Add explicit checks for row and column boundaries and flip direction accordingly

Incorrect calculation of diagonal elements in brute force

Wrong elements collected or missing elements in output

✅ Ensure row + col equals diagonal index and indices are within matrix bounds

Off-by-one errors in loops for diagonal traversal

Index out of range exceptions or incomplete output

✅ Carefully define loop start and end indices using max and min functions

Using extra space unnecessarily in brute force

Higher memory usage and slower performance

✅ Simulate traversal directly without intermediate storage

🧠
Brute Force (Simulate Each Diagonal Explicitly)
💡 This approach exists to build intuition by explicitly collecting elements diagonal by diagonal, which helps understand the traversal pattern before optimizing.

Intuition

The matrix can be traversed by iterating over each diagonal index sum (row + col) and collecting elements belonging to that diagonal. The direction alternates based on whether the diagonal index is even or odd.

Algorithm

  1. Calculate the total number of diagonals as m + n - 1.
  2. For each diagonal index from 0 to total diagonals - 1:
  3. Collect all elements where row + col equals the diagonal index.
  4. If the diagonal index is even, reverse the collected elements before adding to the result to simulate direction change.
💡 The challenge is to correctly identify elements belonging to each diagonal and reverse them on alternate diagonals to match the zigzag pattern.
</>
Code
from typing import List

def findDiagonalOrder(mat: List[List[int]]) -> List[int]:
    if not mat or not mat[0]:
        return []
    m, n = len(mat), len(mat[0])
    result = []
    for d in range(m + n - 1):
        intermediate = []
        # Determine the start row for this diagonal
        r = 0 if d < n else d - n + 1
        c = d if d < n else n - 1
        while r < m and c >= 0:
            intermediate.append(mat[r][c])
            r += 1
            c -= 1
        if d % 2 == 0:
            result.extend(intermediate[::-1])
        else:
            result.extend(intermediate)
    return result

# Driver code
if __name__ == '__main__':
    matrix = [[1,2,3],[4,5,6],[7,8,9]]
    print(findDiagonalOrder(matrix))  # Expected: [1,2,4,7,5,3,6,8,9]
Line Notes
if not mat or not mat[0]:Handle empty matrix edge case to avoid errors
for d in range(m + n - 1):Iterate over each diagonal index sum
while r < m and c >= 0:Traverse elements along the current diagonal
if d % 2 == 0:Reverse elements on even diagonals to simulate zigzag direction
import java.util.*;

public class DiagonalTraverse {
    public static int[] findDiagonalOrder(int[][] mat) {
        if (mat == null || mat.length == 0) return new int[0];
        int m = mat.length, n = mat[0].length;
        int[] result = new int[m * n];
        int index = 0;
        for (int d = 0; d < m + n - 1; d++) {
            List<Integer> intermediate = new ArrayList<>();
            int r = d < n ? 0 : d - n + 1;
            int c = d < n ? d : n - 1;
            while (r < m && c >= 0) {
                intermediate.add(mat[r][c]);
                r++;
                c--;
            }
            if (d % 2 == 0) {
                Collections.reverse(intermediate);
            }
            for (int num : intermediate) {
                result[index++] = num;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}};
        System.out.println(Arrays.toString(findDiagonalOrder(matrix)));
    }
}
Line Notes
if (mat == null || mat.length == 0)Check for empty input to prevent errors
for (int d = 0; d < m + n - 1; d++)Loop over all diagonals by their index sum
while (r < m && c >= 0)Traverse elements along the diagonal
if (d % 2 == 0)Reverse elements on even diagonals to maintain zigzag order
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

vector<int> findDiagonalOrder(vector<vector<int>>& mat) {
    if (mat.empty() || mat[0].empty()) return {};
    int m = mat.size(), n = mat[0].size();
    vector<int> result;
    for (int d = 0; d < m + n - 1; d++) {
        vector<int> intermediate;
        int r = (d < n) ? 0 : d - n + 1;
        int c = (d < n) ? d : n - 1;
        while (r < m && c >= 0) {
            intermediate.push_back(mat[r][c]);
            r++;
            c--;
        }
        if (d % 2 == 0) {
            reverse(intermediate.begin(), intermediate.end());
        }
        result.insert(result.end(), intermediate.begin(), intermediate.end());
    }
    return result;
}

int main() {
    vector<vector<int>> matrix = {{1,2,3},{4,5,6},{7,8,9}};
    vector<int> res = findDiagonalOrder(matrix);
    for (int num : res) cout << num << " ";
    cout << endl;
    return 0;
}
Line Notes
if (mat.empty() || mat[0].empty())Guard clause for empty matrix input
for (int d = 0; d < m + n - 1; d++)Iterate over each diagonal index sum
while (r < m && c >= 0)Collect elements along the diagonal
if (d % 2 == 0)Reverse elements on even diagonals to simulate zigzag
function findDiagonalOrder(mat) {
    if (!mat || mat.length === 0) return [];
    const m = mat.length, n = mat[0].length;
    const result = [];
    for (let d = 0; d < m + n - 1; d++) {
        const intermediate = [];
        let r = d < n ? 0 : d - n + 1;
        let c = d < n ? d : n - 1;
        while (r < m && c >= 0) {
            intermediate.push(mat[r][c]);
            r++;
            c--;
        }
        if (d % 2 === 0) {
            intermediate.reverse();
        }
        result.push(...intermediate);
    }
    return result;
}

// Test
const matrix = [[1,2,3],[4,5,6],[7,8,9]];
console.log(findDiagonalOrder(matrix)); // [1,2,4,7,5,3,6,8,9]
Line Notes
if (!mat || mat.length === 0)Check for empty matrix to avoid runtime errors
for (let d = 0; d < m + n - 1; d++)Loop over each diagonal by index sum
while (r < m && c >= 0)Traverse elements along the diagonal
if (d % 2 === 0)Reverse elements on even diagonals to maintain zigzag order
⏱
Complexity
TimeO(m*n)
SpaceO(m*n)

We visit each element exactly once and store them in an output array. The intermediate list for each diagonal is at most O(min(m,n)) in size.

💡 For a 100x100 matrix, this means about 10,000 operations, which is efficient enough for medium-sized inputs.
Interview Verdict: Accepted

This approach is straightforward and accepted but can be optimized to avoid extra space for intermediate diagonals.

🧠
Better (Simulate Traversal with Direction Flags and Index Updates)
💡 This approach improves on the brute force by simulating the traversal directly without collecting intermediate diagonals, reducing overhead and improving clarity.

Intuition

Instead of collecting diagonals, we move through the matrix by changing direction when hitting boundaries, toggling between moving up-right and down-left.

Algorithm

  1. Initialize row and column indices at (0,0) and direction as up-right.
  2. While the result array is not full:
  3. Add current element to result, then move in the current direction.
  4. If the next move goes out of bounds, adjust indices and flip direction accordingly.
💡 The tricky part is handling boundary conditions correctly to avoid index errors and ensure the zigzag pattern.
</>
Code
from typing import List

def findDiagonalOrder(mat: List[List[int]]) -> List[int]:
    if not mat or not mat[0]:
        return []
    m, n = len(mat), len(mat[0])
    result = []
    r = c = 0
    direction = 1  # 1 means up-right, -1 means down-left
    while len(result) < m * n:
        result.append(mat[r][c])
        if direction == 1:
            if c == n - 1:
                r += 1
                direction = -1
            elif r == 0:
                c += 1
                direction = -1
            else:
                r -= 1
                c += 1
        else:
            if r == m - 1:
                c += 1
                direction = 1
            elif c == 0:
                r += 1
                direction = 1
            else:
                r += 1
                c -= 1
    return result

# Driver code
if __name__ == '__main__':
    matrix = [[1,2,3],[4,5,6],[7,8,9]]
    print(findDiagonalOrder(matrix))  # Expected: [1,2,4,7,5,3,6,8,9]
Line Notes
direction = 1 # 1 means up-right, -1 means down-leftUse a flag to track current traversal direction
if direction == 1:Handle movement when going up-right
if c == n - 1:If at last column, move down and flip direction
elif r == 0:If at first row, move right and flip direction
import java.util.*;

public class DiagonalTraverse {
    public static int[] findDiagonalOrder(int[][] mat) {
        if (mat == null || mat.length == 0) return new int[0];
        int m = mat.length, n = mat[0].length;
        int[] result = new int[m * n];
        int r = 0, c = 0, idx = 0, direction = 1;
        while (idx < m * n) {
            result[idx++] = mat[r][c];
            if (direction == 1) {
                if (c == n - 1) {
                    r++;
                    direction = -1;
                } else if (r == 0) {
                    c++;
                    direction = -1;
                } else {
                    r--;
                    c++;
                }
            } else {
                if (r == m - 1) {
                    c++;
                    direction = 1;
                } else if (c == 0) {
                    r++;
                    direction = 1;
                } else {
                    r++;
                    c--;
                }
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}};
        System.out.println(Arrays.toString(findDiagonalOrder(matrix)));
    }
}
Line Notes
int r = 0, c = 0, idx = 0, direction = 1;Initialize indices and direction flag
if (direction == 1)Handle up-right movement logic
if (c == n - 1)At last column, move down and flip direction
else if (r == 0)At first row, move right and flip direction
#include <iostream>
#include <vector>

using namespace std;

vector<int> findDiagonalOrder(vector<vector<int>>& mat) {
    if (mat.empty() || mat[0].empty()) return {};
    int m = mat.size(), n = mat[0].size();
    vector<int> result;
    int r = 0, c = 0, direction = 1;
    while ((int)result.size() < m * n) {
        result.push_back(mat[r][c]);
        if (direction == 1) {
            if (c == n - 1) {
                r++;
                direction = -1;
            } else if (r == 0) {
                c++;
                direction = -1;
            } else {
                r--;
                c++;
            }
        } else {
            if (r == m - 1) {
                c++;
                direction = 1;
            } else if (c == 0) {
                r++;
                direction = 1;
            } else {
                r++;
                c--;
            }
        }
    }
    return result;
}

int main() {
    vector<vector<int>> matrix = {{1,2,3},{4,5,6},{7,8,9}};
    vector<int> res = findDiagonalOrder(matrix);
    for (int num : res) cout << num << " ";
    cout << endl;
    return 0;
}
Line Notes
int r = 0, c = 0, direction = 1;Initialize traversal indices and direction flag
if (direction == 1)Branch for moving up-right
if (c == n - 1)If at last column, move down and flip direction
else if (r == 0)If at first row, move right and flip direction
function findDiagonalOrder(mat) {
    if (!mat || mat.length === 0) return [];
    const m = mat.length, n = mat[0].length;
    const result = [];
    let r = 0, c = 0, direction = 1;
    while (result.length < m * n) {
        result.push(mat[r][c]);
        if (direction === 1) {
            if (c === n - 1) {
                r++;
                direction = -1;
            } else if (r === 0) {
                c++;
                direction = -1;
            } else {
                r--;
                c++;
            }
        } else {
            if (r === m - 1) {
                c++;
                direction = 1;
            } else if (c === 0) {
                r++;
                direction = 1;
            } else {
                r++;
                c--;
            }
        }
    }
    return result;
}

// Test
const matrix = [[1,2,3],[4,5,6],[7,8,9]];
console.log(findDiagonalOrder(matrix)); // [1,2,4,7,5,3,6,8,9]
Line Notes
let r = 0, c = 0, direction = 1;Initialize row, column, and direction flag
if (direction === 1)Handle movement when going up-right
if (c === n - 1)If at last column, move down and flip direction
else if (r === 0)If at first row, move right and flip direction
⏱
Complexity
TimeO(m*n)
SpaceO(m*n)

Each element is visited exactly once and appended to the result array without extra intermediate storage.

💡 For a 100x100 matrix, this means about 10,000 operations, which is efficient and uses minimal extra space.
Interview Verdict: Accepted

This approach is more efficient and cleaner than brute force and is a good candidate for coding in interviews.

🧠
Optimal (Index Formula Without Direction Flag)
💡 This approach uses a mathematical formula to compute the exact element indices in the diagonal traversal order, eliminating the need for direction flags or conditionals.

Intuition

Each diagonal is identified by the sum of indices (d = r + c). For each diagonal, the elements can be accessed by calculating row and column indices directly using formulas that depend on whether the diagonal is even or odd.

Algorithm

  1. Calculate total diagonals as m + n - 1.
  2. For each diagonal d, determine the start and end indices of elements in that diagonal.
  3. If d is even, traverse the diagonal from bottom to top; if odd, from top to bottom using index formulas.
  4. Append elements directly to the result array.
💡 The key is to derive the correct formulas for row and column indices for each diagonal and direction.
</>
Code
from typing import List

def findDiagonalOrder(mat: List[List[int]]) -> List[int]:
    if not mat or not mat[0]:
        return []
    m, n = len(mat), len(mat[0])
    result = []
    for d in range(m + n - 1):
        # Determine the start and end row indices for this diagonal
        r_start = max(0, d - n + 1)
        r_end = min(d, m - 1)
        if d % 2 == 0:
            # Even diagonal: traverse from r_end down to r_start
            for r in range(r_end, r_start - 1, -1):
                c = d - r
                result.append(mat[r][c])
        else:
            # Odd diagonal: traverse from r_start up to r_end
            for r in range(r_start, r_end + 1):
                c = d - r
                result.append(mat[r][c])
    return result

# Driver code
if __name__ == '__main__':
    matrix = [[1,2,3],[4,5,6],[7,8,9]]
    print(findDiagonalOrder(matrix))  # Expected: [1,2,4,7,5,3,6,8,9]
Line Notes
r_start = max(0, d - n + 1)Calculate the first row index in the diagonal
r_end = min(d, m - 1)Calculate the last row index in the diagonal
if d % 2 == 0:Traverse diagonals in different directions based on parity
c = d - rColumn index is derived from diagonal index minus row index
import java.util.*;

public class DiagonalTraverse {
    public static int[] findDiagonalOrder(int[][] mat) {
        if (mat == null || mat.length == 0) return new int[0];
        int m = mat.length, n = mat[0].length;
        int[] result = new int[m * n];
        int idx = 0;
        for (int d = 0; d < m + n - 1; d++) {
            int rStart = Math.max(0, d - n + 1);
            int rEnd = Math.min(d, m - 1);
            if (d % 2 == 0) {
                for (int r = rEnd; r >= rStart; r--) {
                    int c = d - r;
                    result[idx++] = mat[r][c];
                }
            } else {
                for (int r = rStart; r <= rEnd; r++) {
                    int c = d - r;
                    result[idx++] = mat[r][c];
                }
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}};
        System.out.println(Arrays.toString(findDiagonalOrder(matrix)));
    }
}
Line Notes
int rStart = Math.max(0, d - n + 1);Calculate starting row index for diagonal d
int rEnd = Math.min(d, m - 1);Calculate ending row index for diagonal d
if (d % 2 == 0)Traverse diagonals in reverse order for even d
int c = d - r;Column index derived from diagonal and row indices
#include <iostream>
#include <vector>

using namespace std;

vector<int> findDiagonalOrder(vector<vector<int>>& mat) {
    if (mat.empty() || mat[0].empty()) return {};
    int m = mat.size(), n = mat[0].size();
    vector<int> result;
    for (int d = 0; d < m + n - 1; d++) {
        int rStart = max(0, d - n + 1);
        int rEnd = min(d, m - 1);
        if (d % 2 == 0) {
            for (int r = rEnd; r >= rStart; r--) {
                int c = d - r;
                result.push_back(mat[r][c]);
            }
        } else {
            for (int r = rStart; r <= rEnd; r++) {
                int c = d - r;
                result.push_back(mat[r][c]);
            }
        }
    }
    return result;
}

int main() {
    vector<vector<int>> matrix = {{1,2,3},{4,5,6},{7,8,9}};
    vector<int> res = findDiagonalOrder(matrix);
    for (int num : res) cout << num << " ";
    cout << endl;
    return 0;
}
Line Notes
int rStart = max(0, d - n + 1);Calculate first row index for diagonal d
int rEnd = min(d, m - 1);Calculate last row index for diagonal d
if (d % 2 == 0)Traverse diagonals in reverse order for even d
int c = d - r;Compute column index from diagonal and row
function findDiagonalOrder(mat) {
    if (!mat || mat.length === 0) return [];
    const m = mat.length, n = mat[0].length;
    const result = [];
    for (let d = 0; d < m + n - 1; d++) {
        const rStart = Math.max(0, d - n + 1);
        const rEnd = Math.min(d, m - 1);
        if (d % 2 === 0) {
            for (let r = rEnd; r >= rStart; r--) {
                const c = d - r;
                result.push(mat[r][c]);
            }
        } else {
            for (let r = rStart; r <= rEnd; r++) {
                const c = d - r;
                result.push(mat[r][c]);
            }
        }
    }
    return result;
}

// Test
const matrix = [[1,2,3],[4,5,6],[7,8,9]];
console.log(findDiagonalOrder(matrix)); // [1,2,4,7,5,3,6,8,9]
Line Notes
const rStart = Math.max(0, d - n + 1);Calculate starting row index for diagonal d
const rEnd = Math.min(d, m - 1);Calculate ending row index for diagonal d
if (d % 2 == 0)Traverse diagonals in reverse order for even d
const c = d - r;Column index derived from diagonal and row indices
⏱
Complexity
TimeO(m*n)
SpaceO(m*n)

Each element is visited once and appended directly without extra overhead or direction flags.

💡 This approach is clean and efficient, suitable for large matrices where clarity and speed matter.
Interview Verdict: Accepted

This is the most optimal and elegant approach to code in interviews for this problem.

📊
All Approaches - One-Glance Tradeoffs
💡 The optimal approach (3) is recommended for interviews due to clarity and efficiency; approach 2 is a good fallback; approach 1 is mainly for understanding.
ApproachTimeSpaceStack RiskReconstructUse In Interview
1. Brute ForceO(m*n)O(m*n) extra for intermediate diagonalsNoN/AMention only - never code
2. Better (Simulate Traversal)O(m*n)O(m*n) output onlyNoN/AGood to code if stuck on brute force
3. Optimal (Index Formula)O(m*n)O(m*n) output onlyNoN/ABest approach to code in interviews
💼
Interview Strategy
💡 Use this guide to understand the problem deeply, practice multiple approaches, and prepare to explain your reasoning clearly in interviews.

How to Present

Step 1: Clarify input size and constraints.Step 2: Describe the brute force approach by collecting diagonals explicitly.Step 3: Optimize by simulating traversal with direction flags.Step 4: Present the optimal index formula approach for clean code.Step 5: Write code and test edge cases.

Time Allocation

Clarify: 2min → Approach: 5min → Code: 10min → Test: 3min. Total ~20min

What the Interviewer Tests

Interviewer tests your ability to handle matrix boundaries, direction changes, and index calculations without errors.

Common Follow-ups

  • How would you handle very large matrices efficiently? → Use the optimal approach with O(m*n) time and O(1) extra space.
  • Can you modify the traversal to start from bottom-left? → Adjust starting indices and direction logic accordingly.
💡 Follow-ups test your flexibility in adapting traversal logic and optimizing for constraints.
🔍
Pattern Recognition

When to Use

1) Asked to traverse matrix diagonally; 2) Direction changes after each diagonal; 3) Need to output elements in zigzag order; 4) Matrix boundaries affect traversal.

Signature Phrases

diagonal orderzigzag traversaldirection changesmatrix boundaries

NOT This Pattern When

Simple row-wise or column-wise traversal problems without direction flips

Similar Problems

Zigzag Conversion - similar zigzag pattern but on stringsSpiral Matrix - matrix traversal with direction changesSnake Pattern Matrix - another directional traversal pattern

Practice

(1/5)
1. Consider the following Python function that computes the sum of the diagonals of a square matrix:
def diagonalSum(mat):
    total = 0
    n = len(mat)
    for i in range(n):
        total += mat[i][i] + mat[i][n - 1 - i]
    if n % 2 == 1:
        total -= mat[n//2][n//2]
    return total

matrix = [[1,2,3],[4,5,6],[7,8,9]]
print(diagonalSum(matrix))
What is the value of total after the loop completes but before the if-condition is applied?
easy
A. 15
B. 25
C. 30
D. 45

Solution

  1. Step 1: Trace the loop iterations

    For i=0: total = 0 + mat[0][0] + mat[0][2] = 0 + 1 + 3 = 4 For i=1: total = 4 + mat[1][1] + mat[1][1] = 4 + 5 + 5 = 14 For i=2: total = 14 + mat[2][2] + mat[2][0] = 14 + 9 + 7 = 30
  2. Step 2: Note that the if-condition has not yet been applied

    The total before subtracting the center element is 30.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Sum of diagonals before center correction is 30 [OK]
Hint: Sum both diagonals first, then adjust center if needed [OK]
Common Mistakes:
  • Forgetting to subtract center element once
  • Double counting center element
  • Off-by-one in indices
2. You are given an n x n matrix representing an image. The task is to rotate the image by 90 degrees clockwise in-place, without using extra space. Which of the following approaches guarantees an optimal in-place solution with O(1) extra space and O(n²) time complexity?
easy
A. Perform a layer-by-layer rotation by swapping four elements at a time in-place for each layer of the matrix.
B. Apply a dynamic programming approach to store intermediate rotations and build the final rotated matrix.
C. Use a brute force approach by creating a new matrix and copying elements to their rotated positions.
D. Transpose the matrix and then reverse each column to achieve the rotation.

Solution

  1. Step 1: Understand the problem constraints

    The problem requires rotating the matrix in-place with O(1) extra space and O(n²) time.
  2. Step 2: Evaluate approaches

    Brute force uses extra space, DP is unrelated, and transposing then reversing columns rotates counterclockwise, not clockwise. Layer-by-layer four-way swaps correctly rotate clockwise in-place.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Layer-by-layer swaps rotate in-place with correct direction and complexity [OK]
Hint: Layer-by-layer four-way swaps rotate in-place clockwise [OK]
Common Mistakes:
  • Confusing transpose+reverse columns with clockwise rotation
  • Using extra space when in-place is required
3. What is the time complexity of the optimal in-place Game of Life solution that encodes states using 4 integer values, given an m x n board?
medium
A. O(m + n) since only rows and columns are scanned
B. O(m * n * 8 * 2) due to checking neighbors twice
C. O(m * n * m * n) because each cell checks all other cells as neighbors
D. O(m * n) because each cell and its neighbors are processed in constant time

Solution

  1. Step 1: Identify loops and operations

    Outer loops iterate over all m*n cells. For each cell, 8 neighbors are checked in constant time.
  2. Step 2: Calculate total operations

    Total operations = m*n*8 = O(m*n), since 8 is constant.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Neighbor checks are constant per cell -> linear in board size [OK]
Hint: Neighbor checks are constant per cell, so linear overall [OK]
Common Mistakes:
  • Mistaking neighbor checks as nested loops over entire board
  • Counting neighbor checks twice incorrectly
  • Confusing linear scan with quadratic complexity
4. The following code attempts to compute the sum of the diagonals of a square matrix. Identify the line that contains a subtle bug causing incorrect results for odd-sized matrices.
def diagonalSum(mat):
    total = 0
    n = len(mat)
    for i in range(n):
        total += mat[i][i] + mat[i][n - 1 - i]
    if n % 2 == 1:
        total += mat[n//2][n//2]  # Bug here
    return total
medium
A. Line 5: total += mat[i][i] + mat[i][n - 1 - i]
B. Line 8: total += mat[n//2][n//2] # Bug here
C. Line 7: if n % 2 == 1:
D. Line 4: for i in range(n):

Solution

  1. Step 1: Understand double counting of center element

    For odd n, the center element mat[n//2][n//2] is added twice in the loop.
  2. Step 2: Identify the fix

    The code should subtract the center element once to avoid double counting, but line 8 adds it again, increasing total incorrectly.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Adding center element again causes sum to be too large [OK]
Hint: Center element must be subtracted once if n is odd [OK]
Common Mistakes:
  • Adding instead of subtracting center element
  • Incorrect index calculation for secondary diagonal
  • Ignoring odd-sized matrix special case
5. What is the space complexity of the optimal in-place layer-by-layer rotation algorithm for an n x n matrix, and why might some candidates mistakenly think it is higher?
medium
A. O(n^2) because the entire matrix is modified in place.
B. O(log n) because the algorithm processes layers recursively.
C. O(n) due to the recursion stack or auxiliary arrays used during rotation.
D. O(1) because only a fixed number of variables are used regardless of matrix size.

Solution

  1. Step 1: Identify space usage

    The algorithm uses only a few variables (indices, temp storage) regardless of matrix size.
  2. Step 2: Understand common misconceptions

    Some think space is O(n) or more due to confusion with extra matrix or recursion, but no extra arrays or recursion are used.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Only constant extra variables used, so space is O(1) [OK]
Hint: In-place means constant extra space regardless of input size [OK]
Common Mistakes:
  • Confusing time complexity with space
  • Assuming recursion or extra arrays are used
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