Skip to main content

Count Triplets HackerRank solution in Java with Explanation (Dictionaries and Hashmaps Problem)

Java solution for Count Triplets HackerRank Problem

Count Triplets HackerRank solution in Java with Explanation

Problem Description :

You are given an array and you need to find number of tripets of indices (i, j, k) such that the elements at those indices are in geometric progression for a given common ratio r and i < j < k.

Example 1 :

Input :

arr = [1, 4, 16, 64], r = 4

Output :

There are [1, 4, 16] and [4, 16, 64] at indices (0, 1, 2) and (1, 2, 3). So answer is 2.

Explanation :

r is 4 so we have to multiply by 4.

1 * 4 = 4
4 * 4 = 16
16 * 4 = 64

Example 2 :

arr = [1, 2, 2, 4], r = 2

Output :

There are 2 triplets in satisfying our criteria, whose indices are (0, 1, 3) and (0, 2, 3).

See full description on Hackerrank :

In this solution, we will use HashMap. So lets see solution.

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;

public class Solution {

    // Complete the countTriplets function below.
    private static long countTriplets(List<Long> arr, long ratio) {
        Map<Long, Long> leftMap = new HashMap<>();
        Map<Long, Long> rightMap = new HashMap<>();

        for (long number : arr) {
            rightMap.put(number, rightMap.getOrDefault(number, 0L) + 1);
        }

        long totalTriplets = 0;

        for (int i = 0; i < arr.size(); i++) {
            long current = arr.get(i);
            long left = 0, right = 0;

            rightMap.put(current, rightMap.getOrDefault(current, 0L) - 1);

            if (leftMap.containsKey(current / ratio) && current % ratio == 0) {
                left = leftMap.get(current / ratio);
            }

            if (rightMap.containsKey(current * ratio))
                right = rightMap.get(current * ratio);

            totalTriplets += left * right;

            leftMap.put(current, leftMap.getOrDefault(current, 0L) + 1);

        }
        return totalTriplets;
    }

    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")));

        String[] nr = bufferedReader.readLine().replaceAll("\\s+$", "").split(" ");

        int n = Integer.parseInt(nr[0]);

        long r = Long.parseLong(nr[1]);

        List<Long> arr = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
            .map(Long::parseLong)
            .collect(toList());

        long ans = countTriplets(arr, r);

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

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

Solution Explanation :

  • We have given Array as arr and Ratio as r. 
  • So we will loop through entire array, First put all array integer on rightMap with value frequency. As we going forward, put left index integers of current index in leftMap and substarct current index value in rightMap.
  • getOrDefault() method of map used to get the value mapped with specified key. If no value is mapped with the provided key then the default value is returned (in our case 0).
  • We have to check only 3 indices, so in left variable assign (current / r) value and in right variable assign (current * r) value.
    • arr = [1, 4, 16, 64], r = 4
    • So if we are on index 1 value 4 then left become (current / r) = 1 and right become (current * 4) = 16, so we find 3 indices that matches our condition.
  • Last we check, multiple of right and left integer.
  • Return totalTriplets.

Output Explanation :

arr = [1, 5, 5, 25, 125], r = 5

  • leftMap = [], rightMap = [1 = 1, 5 = 2, 25 = 1, 125 = 1], totalTriplets = 0
  • i = 0
    • left = 0, right = 0, current = 1
    • Decrement current value in map | rightMap = [1 = 0, 5 = 2, 25 = 1, 125 = 1] 
    • leftMap.containsKey(0) && 1 % 5 == 0 becomes false
    • rightMap.containsKey(5) becomes true
      • right = 2  
    • totalTriplets += left*right | 0 = 0*2 
    • leftMap = [1 = 1]

  • i = 1, leftMap = [1 = 1], rightMap = [1 = 0, 5 = 2, 25 = 1, 125 = 1], totalTriplets = 0
    • left = 0, right = 0, current = 5
    • rightMap = [1 = 0, 5 = 1, 25 = 1, 125 = 1]
    • leftMap contains key 1 && 5 % 5 == 0 becomes true
      • left =1 
    • rightMap containsKey(25) becomes true
      • right = 1    
    • totalTriplets = 1*1+0
    • leftMap = [1 = 1, 5 = 1]

  • i = 2, leftMap = [1 = 1, 5 = 1], rightMap = [1 = 0, 5 = 1, 25 = 1, 125 = 1], totalTriplets = 1
    • left = 0, right = 0, current = 5
    • rightMap = [1 = 0, 5 = 0, 25 = 1, 125 = 1]
    • leftMap contains key 1 && 5 % 5 == 0 becomes true
      • left =1 
    • rightMap containsKey(25) becomes true
      • right = 1    
    • totalTriplets = 1*1+1 = 2
    • leftMap = [1 = 1, 5 = 2]

  • i = 3, leftMap = [1 = 1, 5 = 2], rightMap = [1 = 0, 5 = 0, 25 = 1, 125 = 1], totalTriplets = 2
    • left = 0, right = 0, current = 25
    • rightMap = [1 = 0, 5 = 0, 25 = 0, 125 = 1]
    • leftMap contains key 5 && 25 % 5 == 0 becomes true
      • left = 2
    • rightMap containsKey(125) becomes true
      • right = 1    
    • totalTriplets = 2*1+2 = 4
    • leftMap = [1 = 1, 5 = 2, 25 = 1]

  •  i = 4, leftMap = [1 = 1, 5 = 2, 25 = 1], rightMap = [1 = 0, 5 = 0, 25 = 0, 125 = 1], totalTriplets =4
    • left = 0, right = 0, current = 125
    • rightMap = [1 = 0, 5 = 0, 25 = 0, 125 = 0]
    • leftMap contains key 25 && 125 % 5 == 0 becomes true
      • left = 2
    • rightMap containsKey(625) becomes false. 
    • totalTriplets = 2*0+2 = 4
    • leftMap = [1 = 1, 5 = 2, 25 = 1, 125 = 1]

  •  Return totalTriplets = 4

 

Happy Learning. Happy Coding.

Other HackerRank solutions in Java :

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 java.util.st

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 last