JuniorCodeOccasionalNot answered yet
Absolute difference of a square matrix's two diagonals
Given an n x n matrix of integers, return the absolute difference between the sum of its main diagonal and the sum of its anti-diagonal.
Requirements:
- Main diagonal cell is
m[i][i]; anti-diagonal cell ism[i][n-1-i]. - Return a non-negative integer.
def diagonal_diff(m):
# your code here
Write the implementation.
Loop i from 0 to n-1, summing m[i][i] for the main diagonal and m[i][n-1-i] for the anti-diagonal, then return abs(main - anti). The key index is n-1-i for the anti-diagonal — off-by-one here (using n-i or counting bottom-up) is the classic bug. A single pass is O(n).
- ✗Using
n-iinstead ofn-1-ifor the anti-diagonal column - ✗Forgetting to take the absolute value of the difference
- ✗Not converting parsed string cells to
intbefore summing
- →Why is the anti-diagonal column index
n-1-irather thann-i? - →How would you read this matrix from a multi-line string before summing?
Contents
Task
Implement diagonal_diff: return the absolute difference of the main and anti-diagonal sums of a square matrix.
Solution
def diagonal_diff(m):
n = len(m)
main = sum(m[i][i] for i in range(n))
anti = sum(m[i][n - 1 - i] for i in range(n))
return abs(main - anti)
Key points
- Main diagonal is
m[i][i], anti-diagonal ism[i][n-1-i]; the-1is the off-by-one trap. - A single pass over the rows is O(n), O(1) space.
- Don't forget
absand converting cells tointif the matrix arrived as a string.
Contents