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

Queen's Attack II HackerRank Solution in Java with Explanation

Queen's Attack II Problem's Solution in Java (Chessboard Problem)   Problem Description : You will be given a square chess board with one queen and a number of obstacles placed on it. Determine how many squares the queen can attack.  A queen is standing on an n * n chessboard. The chess board's rows are numbered from 1 to n, going from bottom to top. Its columns are numbered from 1 to n, going from left to right. Each square is referenced by a tuple, (r, c), describing the row r and column c, where the square is located. The queen is standing at position (r_q, c_q). In a single move, queen can attack any square in any of the eight directions The queen can move: Horizontally (left, right) Vertically (up, down) Diagonally (four directions: up-left, up-right, down-left, down-right) The queen can move any number of squares in any of these directions, but it cannot move through obstacles. Input Format : n : The size of the chessboard ( n x n ). k : The number of obstacles...

Java Hashset HackerRank Solution | Programming Blog

Java Hashset HackerRank Solution with Explanation   Problem Statement :- In computer science, a set is an abstract data type that can store certain values, without any particular order, and no repeated values. {1,2,3} is an example of a set, but {1,2,2} is not a set. Today you will learn how to use sets in java by solving this problem. You are given n pairs of strings. Two pairs (a,b) and (c,d) are identical if a = c and b = d. That also implies (a,b) is not same as (b,a). After taking each pair as input, you need to print number of unique pairs you currently have. See full problem description in HackerRank Website :- https://www.hackerrank.com/challenges/java-hashset/problem Let's see solution of problem. import java.util.HashSet; import java.util.Scanner; public class Solution {     public static void main(String[] args) {         Scanner s = new Scanner(System.in);         System.out.println("Enter tot...