Diagonal Difference

Sort by

recency

|

160 Discussions

|

  • + 0 comments

    Solution in Python 3

    def diagonalDifference(arr):
        size = len(arr)
        lr = 0
        rl = 0
        for i in range(size):
            lr += arr[i][i]
            rl += arr[i][(size - 1) - i]
        return abs(lr - rl)
    
  • + 0 comments

    Here is a Python 3 solution:

    def diagonalDifference(arr: list[list[int]]) -> int:
        return abs(sum(row[i] - row[~i] for i, row in enumerate(arr)))
    
  • + 0 comments

    My Typescript solution:

    function diagonalDifference(arr: number[][]): number {
        let ltrDiagonalSum = 0;
        let rtlDiagonalSum = 0;
        const length = arr.length;
        
        for (let i = 0; i < length; i++) {
            ltrDiagonalSum += arr[i][i];
            rtlDiagonalSum += arr[i][length - 1 - i];
        }
        
        return Math.abs(ltrDiagonalSum - rtlDiagonalSum);
    }
    
  • + 0 comments

    pyton 3

    def diagonalDifference(arr):
        t = 0
        s = len(arr)
        for i in range(s):
            t = t + arr[i][i] - arr[s-i-1][i]
        return abs(t)
    
  • + 0 comments

    A rust solution:

    fn diagonalDifference(arr: &[Vec<i32>]) -> i32 {
        let len = arr.len();
        let (diag_first, diag_second) = (0..len).fold((0, 0), |mut acc, i| {
            acc.0 += arr[i][i];
            acc.1 += arr[i][len - 1 - i];
            acc
        });
        (diag_first - diag_second).abs()
    }