Skip to main content

Diagonal Difference in Java | Find difference between sums of two diagonals | HackerRank problem

Java Solution for HackerRank Diagonal Difference problem 

Diagonal Difference in Java | Hackerrank solution

Problem Description :

Given a square matrix, calculate the absolute difference between the sums of its diagonals. 

For example, the square matrix arr is shown below: 

1 2 3
4 5 6
9 8 9

The left to right diagonal = 1 + 5 + 9 = 15 The right to left diagonal = 3 + 5 + 9 = 17 Their absolute difference is | 15 - 17 | = 2.

See full description :

Sample Input :

Row and Column Size : 3

2 4 6
1 3 5
7 8 -9

Sample Output : 2

Explanation : left to right diagonal = 2 + 3 - 9 = -4. The right to left diagonal = 6 + 3 + 7 = 16. So the absolute difference is | -4 - 16 = 20 |

Left to right and right to left diagonal

Lest see solution and its explanation.

Solution 1

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

    public static int diagonalDifference(List<List<Integer>> arr) {
   
        int leftDiagonal = 0;
        int rightDiagonal = 0;
    
        for (int i = 0; i < arr.size(); i++) {
    leftDiagonal += arr.get(i).get(i);
    rightDiagonal += arr.get(i).get((arr.get(i).size() - 1) - i);
}
        
        return Math.abs(leftTotal - rightTotal);

    }


}

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(
            new FileWriter(System.getenv("OUTPUT_PATH")));

        int n = Integer.parseInt(bufferedReader.readLine().trim());

        List<List<Integer>> arr = new ArrayList<>();

        IntStream.range(0, n).forEach(i -> {
            try {
                arr.add(
                    Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "")
                        .split(" "))
                        .map(Integer::parseInt)
                        .collect(toList())
                );
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });

        int result = Result.diagonalDifference(arr);

        bufferedWriter.write(String.valueOf(result));
        bufferedWriter.newLine();

        bufferedReader.close();
        bufferedWriter.close();
    }
}

Code explanation :

  • We already have Integer of 2D List. We just have to add logic in given method.
  • In this problem, we just need to return absolute (Positive value) Sum of left to right diagonal - Sum of right to left diagonal.
  • Define two integer value leftDiagonal, rightDiagonal and initialize with 0 value. 
  • Traverse through given 2D list from 0 to list size and store sum of left to right diagonal value to leftDiagonal variable and right to left diagonal value to rightDiagonal variable. 
    • In loop using 3 * 3 matrix, we are getting value of leftDiagonal through following index : 0 + 4 + 8, and right Diagonal through following index : 2 + 4 + 6.
  • list.get(0).get(0) means 0th row and 0th column.
  • Last return absolute value of leftDiagonal - rightDiagonal value.

Output explanation :

List = 1st row [1, 2, 3],
           2nd row [4, 5, 6],
           3rd row [9, 8, 9]

  • i = 0, leftDiagonal = 0, rightDiagonal = 0, list size = 3
    • leftDiagonal = 0 + arr.get(0).get(0) = [0, 0]
      leftDiagonal  =  0 + 1 = 1
    • rightDiagonal = 0 + arr.get(0).get((arr.get(0).size() - 1) - 0) = [0, 2]
      rightDiagonal = 0 + 3 = 3

  • i = 1, leftDiagonal = 1, rightDiagonal = 3
    • leftDiagonal = 1 + arr.get(1).get(1) = [1, 1]
      leftDiagonal  =  1 + 5 = 6
    • rightDiagonal = 3 + arr.get(1).get((arr.get(1).size() - 1) - 1) = [1, 1]
      rightDiagonal = 3 + 5 = 8

  • i = 2, leftDiagonal = 6, rightDiagonal = 8
    • leftDiagonal = 6 + arr.get(2).get(2) = [2, 2]
      leftDiagonal  =  6 + 9 = 15
    • rightDiagonal = 8 + arr.get(2).get((arr.get(2).size() - 1) - 2) = [2, 0]
      rightDiagonal = 8 + 9 = 17

  • leftDiagonal = 15, rightDiagonal = 17
  • Math.abs(15 - 17) = 2

We can directly take left and right diagonal value one by one through loop and return answer.

Solution 2

public static int diagonalDifference(List<List<Integer>> arr) {
        
        int difference = 0;
        for (int i = 0; i < arr.size(); i++) {
            difference += arr.get(i).get(i) - arr.get(i).get((arr.get(i).size()-1)-i);
        }
        
        return Math.abs(difference);
}

Lets see another solution using java 8

Solution 3

int leftDiagonal = arr.stream()
                .map(i -> i.get(arr.indexOf(i)))
                .collect(Collectors.toList())
                .stream()
                .reduce(0, (a, b) -> a+b);

int rightDiagonal = arr.stream()
                .map(i -> i.get((arr.size() - 1) - arr.indexOf(i)))
                .collect(Collectors.toList())
                .stream()
                .reduce(0, (a, b) -> a+b);

return Math.abs(leftDiagonal - rightDiagonal);

Learn more about Java 8 Stream API map(), collect() and reduce() methods.

  1. collect() method in Java 8 
  2. map() method in Java 8
  3. reduce() method in Java 8 

Happy Coding.

See other HackerRank problem and its solution with explanation :

 

Comments

Popular posts from this blog

Plus Minus HackerRank Solution in Java | Programming Blog

Java Solution for HackerRank Plus Minus Problem Given an array of integers, calculate the ratios of its elements that are positive , negative , and zero . Print the decimal value of each fraction on a new line with 6 places after the decimal. Example 1 : array = [1, 1, 0, -1, -1] There are N = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000 and 1/5 = 0.200000. Results are printed as:  0.400000 0.400000 0.200000 proportion of positive values proportion of negative values proportion of zeros Example 2 : array = [-4, 3, -9, 0, 4, 1]  There are 3 positive numbers, 2 negative numbers, and 1 zero in array. Following is answer : 3/6 = 0.500000 2/6 = 0.333333 1/6 = 0.166667 Lets see solution Solution 1 import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static jav...

Flipping the Matrix HackerRank Solution in Java with Explanation

Java Solution for Flipping the Matrix | Find Highest Sum of Upper-Left Quadrant of Matrix Problem Description : Sean invented a game involving a 2n * 2n matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times. The goal of the game is to maximize the sum of the elements in the n *n submatrix located in the upper-left quadrant of the matrix. Given the initial configurations for q matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal.  Input : matrix = [[1, 2], [3, 4]] Output : 4 Input : matrix = [[112, 42, 83, 119], [56, 125, 56, 49], [15, 78, 101, 43], [62, 98, 114, 108]] Output : 119 + 114 + 56 + 125 = 414 Full Problem Description : Flipping the Matrix Problem Description   Here we can find solution using following pattern, So simply we have to find Max of same number of box like (1,1,1,1). And ...