Bird
Raised Fist0
Interview PrepmatriceseasyAmazonGoogle

Matrix Diagonal Sum

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

int diagonalSum(vector<vector<int>>& mat) {
    // Write your solution here
    return 0;
}
function diagonalSum(mat) {
    // Write your solution here
}
Coming soon
0/10
Common Bugs to Avoid
Wrong: 30Summing both diagonals without subtracting the center element for odd n.✅ Subtract mat[n//2][n//2] once after summing both diagonals if n is odd.
Wrong: 20Summing only the primary diagonal and ignoring the secondary diagonal.✅ Sum both primary diagonal mat[i][i] and secondary diagonal mat[i][n-1-i].
Wrong: 15Incorrect indexing of secondary diagonal, e.g., using mat[i][i] twice or wrong indices.✅ Use mat[i][n-1-i] for secondary diagonal elements.
Wrong: 0Subtracting center element even when n=1, causing zero result.✅ Do not subtract center element if n=1.
Wrong: TLEUsing nested loops O(n^2) for large n causing timeout.✅ Use single loop O(n) summation of diagonals.
✓
Test Cases
t1_01basic
Input{"mat":[[1,2,3],[4,5,6],[7,8,9]]}
Expected25

Primary diagonal sum = 1 + 5 + 9 = 15; Secondary diagonal sum = 3 + 5 + 7 = 15; Center element 5 counted twice, so subtract once: 15 + 15 - 5 = 25.

t1_02basic
Input{"mat":[[5,1,2,3],[4,5,6,7],[8,9,5,1],[2,3,4,5]]}
Expected40

Primary diagonal sum = 5 + 5 + 5 + 5 = 20; Secondary diagonal sum = 3 + 6 + 9 + 2 = 20; No center overlap since n=4 is even; total = 20 + 20 = 40.

t2_01edge
Input{"mat":[[42]]}
Expected42

1x1 matrix has only one element which is both diagonals and center; sum is that element.

t2_02edge
Input{"mat":[[1,2],[3,4]]}
Expected10

Primary diagonal sum = 1 + 4 = 5; Secondary diagonal sum = 2 + 3 = 5; No center overlap for even n; total = 10.

t2_03edge
Input{"mat":[[100,100,100],[100,100,100],[100,100,100]]}
Expected500

Primary diagonal sum = 100 + 100 + 100 = 300; Secondary diagonal sum = 100 + 100 + 100 = 300; Center element 100 counted twice, subtract once: 300 + 300 - 100 = 500.

t2_04edge
Input{"mat":[[1]]}
Expected1

Single element matrix to confirm no subtraction of center element when n=1.

t3_01corner
Input{"mat":[[1,2,3],[4,5,6],[7,8,9]]}
Expected25

Same as canonical example to catch greedy approach errors.

t3_02corner
Input{"mat":[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]}
Expected68

Primary diagonal sum = 1 + 6 + 11 + 16 = 34; Secondary diagonal sum = 4 + 7 + 10 + 13 = 34; Even n, no center subtraction; total = 68.

t3_03corner
Input{"mat":[[1,2,3],[4,5,6],[7,8,9]]}
Expected25

Canonical example to catch confusion about subtracting center element twice or not at all.

t4_01performance
Input{"mat":[[100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100],[100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100],[100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100],[100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100],[100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100],[100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100],[100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100],[100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100],[100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100],[100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100]]}
⏱ Performance - must finish in 2000ms

n=100 matrix with max values; O(n) solution must complete within 2 seconds.

Practice

(1/5)
1. Consider the following Python function that returns the spiral order of a matrix. What is the output of spiralOrder([[1,2],[3,4]])?
easy
A. [1, 2, 3, 4]
B. [1, 2, 4, 3]
C. [1, 3, 4, 2]
D. [1, 4, 3, 2]

Solution

  1. Step 1: Trace first iteration

    Top=0, Bottom=1, Left=0, Right=1. Append top row: [1, 2]. Increment top to 1.
  2. Step 2: Trace right column and subsequent steps

    Append right column from row 1 to 1: [4]. Decrement right to 0. Since top <= bottom, append bottom row reversed: [3]. Decrement bottom to 0. Left <= right, but now left=0, right=0, top=1, bottom=0 so loop ends.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Output matches clockwise spiral traversal [OK]
Hint: Trace boundaries and append order carefully [OK]
Common Mistakes:
  • Appending rows or columns in wrong order
  • Off-by-one errors in loops
  • Not updating boundaries correctly
2. Consider this buggy code snippet for diagonal traversal. Which line contains the subtle bug that causes incorrect traversal or index errors?
def findDiagonalOrder(mat):
    if not mat or not mat[0]:
        return []
    m, n = len(mat), len(mat[0])
    result = []
    for d in range(m + n - 1):
        r_start = max(0, d - n + 1)
        r_end = min(d, m - 1)
        if d % 2 == 0:
            for r in range(r_start, r_end + 1):  # Bug here: direction wrong
                c = d - r
                result.append(mat[r][c])
        else:
            for r in range(r_end, r_start - 1, -1):
                c = d - r
                result.append(mat[r][c])
    return result
medium
A. Line with 'r_start = max(0, d - n + 1)'
B. Line with 'for r in range(r_start, r_end + 1):' inside even diagonal block
C. Line with 'c = d - r' inside loops
D. Line with 'for d in range(m + n - 1):'

Solution

  1. Step 1: Identify traversal direction for even diagonals

    Even diagonals must traverse from r_end down to r_start (descending).
  2. Step 2: Check loop direction in buggy code

    The loop uses ascending range from r_start to r_end, which is incorrect and causes wrong order or index errors.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Fixing loop direction restores correct traversal [OK]
Hint: Even diagonals traverse downward (descending indices) [OK]
Common Mistakes:
  • Using ascending loop for even diagonals causing order errors
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. What is the time complexity of the optimal in-place boundary shrinking spiral traversal algorithm for an m x n matrix?
medium
A. O(m * n * min(m, n)) due to nested loops over shrinking boundaries
B. O(m + n) because each boundary shrinks linearly
C. O(m * n) because every element is visited exactly once
D. O(m * n + m + n) combining traversal and boundary updates

Solution

  1. Step 1: Identify the number of elements visited

    The algorithm visits each element exactly once, so total operations scale with m*n.
  2. Step 2: Analyze loops and boundary updates

    Though boundaries shrink, the total number of elements processed remains m*n, no nested multiplicative overhead beyond that.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Each element processed once -> O(m*n) [OK]
Hint: Count total elements visited, not loop nesting [OK]
Common Mistakes:
  • Confusing boundary shrinking loops as nested multiplicative loops
  • Ignoring that each element is visited once
  • Adding linear terms incorrectly
5. Examine the following buggy code snippet for Sudoku validation using bitmasking:
def isValidSudoku(board):
    rows = [0] * 9
    cols = [0] * 9
    boxes = [0] * 9
    for i in range(9):
        for j in range(9):
            if board[i][j] == '.':
                continue
            val = ord(board[i][j]) - ord('1')
            mask = 1 << val
            box_index = i // 3 + (j // 3) * 3
            if (rows[i] & mask) or (cols[j] & mask) or (boxes[box_index] & mask):
                return false
            rows[i] |= mask
            cols[j] |= mask
            boxes[box_index] |= mask
    return true
What is the bug in this code?
medium
A. The rows and cols arrays should be initialized with sets, not integers.
B. The mask calculation is wrong; it should be 1 << (val + 1).
C. The code incorrectly includes '.' in the bitmask checks.
D. The box_index calculation is incorrect; it should be (i // 3) * 3 + (j // 3).

Solution

  1. Step 1: Analyze box_index calculation

    The code uses box_index = i // 3 + (j // 3) * 3, which swaps row and column grouping.
  2. Step 2: Correct formula for box_index

    The correct formula is (i // 3) * 3 + (j // 3) to map 3x3 boxes properly.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Incorrect box_index causes missed duplicates in boxes [OK]
Hint: Box index formula must map 3x3 boxes correctly [OK]
Common Mistakes:
  • Swapping row and column in box index
  • Misusing bitmask shifts
  • Including '.' in checks
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