Diagonal Difference

Sort by

recency

|

315 Discussions

|

  • + 0 comments
    # Write your code here
    principal = 0
    secondary = 0
    n = len(arr)
    
    for i in range(0, n):
    		principal+=arr[i][i]
    		secondary+=arr[i][n-i-1]
    
    absDiff = abs(principal-secondary)
    return absDiff
    

    undefined

  • + 0 comments

    Java Solution:

        public static int diagonalDifference(List<List<Integer>> arr) {
    
            int leftSum = 0;
            int rightSum = 0;
            
            for(int i=0; i<arr.size();i++){
                List<Integer> row = arr.get(i);
                leftSum = leftSum + row.get(i);
                rightSum = rightSum + row.get(row.size() -1  - i);
            }
            
            return leftSum > rightSum ? (leftSum - rightSum) : (rightSum - leftSum);
        }
    
  • + 0 comments
    public static int diagonalDifference(List<List<Integer>> matrix) {
        int primaryDiagonalSum = 0;
        int secondaryDiagonalSum = 0;
        int n = matrix.size();
        for (int i = 0; i < n; i++) {
            primaryDiagonalSum += matrix.get(i).get(i); // Left-to-right diagonal
            secondaryDiagonalSum += matrix.get(i).get(n - i - 1); // Right-to-left diagonal
        }
        return Math.abs(primaryDiagonalSum - secondaryDiagonalSum);
    }
    
  • + 2 comments

    in python

    def diagonalDifference(arr): # Write your code here i=0 a=-1 l1=[] l2=[] for i in range(len(arr)): l1.append(arr[i][i]) i+=1 for i in range(len(arr)): l2.append(arr[i][a]) a-=1 i+=1 result=(sum(l1)-sum(l2)) return(abs(result))

  • + 1 comment

    in JavaScript:

    function diagonalDifference(arr) {
        const n = arr.length;
        let i = 0;
        let j = 0;
        let k = n - 1;
        let leftDiag = 0;
        let rightDiag = 0;
    
        while (i < n && j < n) {
            leftDiag += arr[i][j];
            rightDiag += arr[i][k];
            i++;
            j++;
            k--;
        }
        
        return Math.abs(leftDiag - rightDiag);
    }