Diagonal Difference

Sort by

recency

|

312 Discussions

|

  • + 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);
    }
    
  • + 0 comments

    int diagonalDifference(vector> arr) {

    int a= 0 , b = 0;
    int size = arr.size();
    
    for(int i = 0; i < size; ++i) {
        a += arr[i][i];
        b += arr[size - 1 - i][i];
    }
    
    return abs(a - b);
    

    }

  • + 0 comments

    JAVA code public static int diagonalDifference(List> arr) { // Write your code here int primaryDiagonalSum = 0; int secondaryDiagonalSum = 0;

    for (int i = 0; i < arr.size(); i++) {
        primaryDiagonalSum += arr.get(i).get(i);
        secondaryDiagonalSum += arr.get(i).get(arr.size() - i - 1);
    }
    
    int diff = Math.abs(primaryDiagonalSum - secondaryDiagonalSum);
    return diff;
    }
    
  • + 0 comments

    short c++ solution

    int diagonalDifference(vector> arr) { int n = arr.size(); int d1 = 0, d2 = 0;

    for (int i = 0; i < n; i++) {
        d1 += arr[i][i];
        d2 += arr[i][n-1-i];
    }
    return abs(d1-d2);
    

    }