Diagonal Difference

Sort by

recency

|

670 Discussions

|

  • + 0 comments
    public static int diagonalDifference(List<List<Integer>> arr) {
        // Write your code here
        
        int size = arr.size();
    
        int primary = 0;
        
        int secondary = 0; 
        
        for(int i=0; i < size; i++){
            
            primary += arr.get(i).get(i);
            secondary += arr.get(i).get(size-1-i);
        }
        
        return Math.abs(primary-secondary);
    
        }
    
  • + 1 comment

    Python:

    def diagonalDifference(arr):
        left, right = 0, 0
        for i in range(len(arr)):
            for j in range(len(arr[i])):
                if i == j:
                    left += arr[i][j]
                if j == len(arr[i]) - 1 - i:
                    right += arr[i][j]
        return abs(left - right)
    
  • + 0 comments

    Only read if you have attempted to solve the problem

    The key to solving this problem is finding the relationship between the row and column index positions when iterating through the 2d array.

    For the main diagonal, the row and column indices will always be equal.

    For the secondary diagonal, the column index will decrease as each row increases. This relationship can be described as col_index = (arr.size() - row_index - 1).

  • + 0 comments

    Python:

    def diagonalDifference(arr): left_diagonal = [] right_diagonal = [] ratio = 0 for i, row in enumerate(arr): last = len(row) -1 - ratio ratio += 1 for j, elem in enumerate(row): if i == j: left_diagonal.append(arr[i][j]) if j == last: right_diagonal.append(arr[i][j])

    return abs(sum(left_diagonal) -  sum(right_diagonal))
    
  • + 1 comment
    typescript
    function diagonalDifference(arr: number[][]): number {
      let left = 0, right = 0, row = 0;
      for (
        let i = 0, j = arr.length - 1;
        i < arr.length && j >= 0; 
        i++, j--
      ) {
        left += arr[row][i];
        right += arr[row][j];
        row++;
      }
      return Math.abs(left - right);
    }