Compute matrix trace and support updates
Company: Anthropic
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates proficiency in matrix manipulation, incremental updates, and complexity analysis, specifically maintaining main-diagonal and anti-diagonal sums under point updates.
Part 1: Compute the main diagonal trace of a square matrix
Constraints
- 0 <= n <= 2000, where n is the number of rows
- -10^9 <= matrix[i][j] <= 10^9
- If the matrix is non-empty, it should be square for a valid input
Examples
Input: ([[1, 2], [3, 4]],)
Expected Output: 5
Explanation: The main diagonal is 1 and 4, so the sum is 5.
Input: ([[7]],)
Expected Output: 7
Explanation: A 1x1 matrix has exactly one diagonal element.
Hints
- The main diagonal consists of entries where the row index equals the column index.
- Before summing, verify that every row has length `n`.
Part 2: Support O(1) trace queries after point updates
Constraints
- 0 <= n <= 2000
- 0 <= q <= 200000, where q is the number of updates
- -10^9 <= matrix[i][j], val <= 10^9
- Updates use 0-based indices
Examples
Input: ([[1, 2], [3, 4]], [(0, 1, 10), (1, 1, 7), (0, 0, -1)])
Expected Output: [5, 8, 6]
Explanation: The first update is off-diagonal, so the trace stays 5. Then 4 becomes 7, making the trace 8. Finally 1 becomes -1, making the trace 6.
Input: ([[5]], [(0, 0, 3), (0, 0, 3)])
Expected Output: [3, 3]
Explanation: A 1x1 matrix's only cell is always on the main diagonal.
Hints
- Do not recompute the whole trace after each update. Store the current trace in a variable.
- Only updates with `i == j` change the trace, and the change is `val - old_value`.
Part 3: Maintain both main-diagonal and anti-diagonal sums under updates
Constraints
- 0 <= n <= 2000
- 0 <= q <= 200000
- -10^9 <= matrix[i][j], val <= 10^9
- Updates use 0-based indices
- For anti-diagonal positions, `i + j == n - 1`
Examples
Input: ([[1, 2, 3], [4, 5, 6], [7, 8, 9]], [(0, 2, 10), (1, 1, 0), (2, 0, -1)])
Expected Output: [(15, 22), (10, 17), (10, 9)]
Explanation: The first update changes only the anti-diagonal. The second update hits the center, so it changes both sums. The third update changes only the anti-diagonal.
Input: ([[1, 2], [3, 4]], [(0, 0, 5), (0, 1, 7)])
Expected Output: [(9, 5), (9, 10)]
Explanation: In a 2x2 matrix, (0,0) is on the main diagonal only, while (0,1) is on the anti-diagonal only.
Hints
- Keep two running sums: one for the main diagonal and one for the anti-diagonal.
- When `n` is odd, the center cell satisfies both `i == j` and `i + j == n - 1`, so one update may affect both sums.