|
| 1 | +/** |
| 2 | + * |
| 3 | + * Problem Statement- |
| 4 | + * [Count Triplets](https://www.hackerrank.com/challenges/count-triplets-1/problem) |
| 5 | + * [Tutorial]() |
| 6 | + * |
| 7 | + */ |
| 8 | +package com.javaaid.dictionaries; |
| 9 | + |
| 10 | +import java.io.IOException; |
| 11 | +import java.util.ArrayList; |
| 12 | +import java.util.HashMap; |
| 13 | +import java.util.List; |
| 14 | +import java.util.Map; |
| 15 | +import java.util.Scanner; |
| 16 | + |
| 17 | +public class CountTriplets { |
| 18 | + |
| 19 | + private static long countTriplets(List<Long> arr, long r) { |
| 20 | + Map<Long, Long> leftMap = new HashMap<>(); |
| 21 | + Map<Long, Long> rightMap = new HashMap<>(); |
| 22 | + |
| 23 | + for (long item : arr) { |
| 24 | + rightMap.put(item, rightMap.getOrDefault(item, 0L) + 1); |
| 25 | + } |
| 26 | + |
| 27 | + long count = 0; |
| 28 | + |
| 29 | + for (int i = 0; i < arr.size(); i++) { |
| 30 | + long midTerm = arr.get(i); |
| 31 | + long c1 = 0, c3 = 0; |
| 32 | + |
| 33 | + rightMap.put(midTerm, rightMap.getOrDefault(midTerm, 0L) - 1); |
| 34 | + |
| 35 | + if (leftMap.containsKey(midTerm / r) && midTerm % r == 0) { |
| 36 | + c1 = leftMap.get(midTerm / r); |
| 37 | + } |
| 38 | + |
| 39 | + if (rightMap.containsKey(midTerm * r)) |
| 40 | + c3 = rightMap.get(midTerm * r); |
| 41 | + |
| 42 | + count += c1 * c3; |
| 43 | + |
| 44 | + leftMap.put(midTerm, leftMap.getOrDefault(midTerm, 0L) + 1); |
| 45 | + |
| 46 | + } |
| 47 | + return count; |
| 48 | + } |
| 49 | + |
| 50 | + public static void main(String[] args) throws IOException { |
| 51 | + Scanner sc = new Scanner(System.in); |
| 52 | + long n = sc.nextLong(); |
| 53 | + long r = sc.nextLong(); |
| 54 | + List<Long> arr = new ArrayList<>(); |
| 55 | + while (n-- > 0) { |
| 56 | + arr.add(sc.nextLong()); |
| 57 | + } |
| 58 | + |
| 59 | + long ans = countTriplets(arr, r); |
| 60 | + System.out.println(ans); |
| 61 | + |
| 62 | + sc.close(); |
| 63 | + } |
| 64 | +} |
0 commit comments