We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Count Triplets
- Discussions
Count Triplets
Count Triplets
+ 0 comments Eritorial transformed into Java. Don't forget to check if number is divisible by r.
// Complete the countTriplets function below. static long countTriplets(List<Long> arr, long r) { HashMap<Long, Long> right = new HashMap<>(); HashMap<Long, Long> left = new HashMap<>(); for (Long num : arr) { right.put(num, right.getOrDefault(num, 0L) + 1); } long tripletsCounter = 0; for (Long num : arr) { if (right.getOrDefault(num, 0L) > 0) { right.put(num, right.get(num) - 1); } if (num % r == 0) { tripletsCounter += right.getOrDefault(num * r, 0L) * left.getOrDefault(num / r, 0L); } left.put(num, left.getOrDefault(num, 0L) + 1); } return tripletsCounter; }
+ 2 comments Hello, using the Editorial suggestion :
function countTriplets(arr, r) { let result = 0 const left = new Map(), right = new Map() arr.forEach((elem) => { const tmp = right.get(elem) || 0 right.set(elem, tmp+1) }) arr.forEach((elem) => { if (right.has(elem)) right.set(elem, right.get(elem) - 1) const c1 = right.get(elem * r) || 0 const c2 = left.get(elem / r) || 0 result += c1 * c2 left.set(elem, (left.get(elem) || 0) + 1) }) return result }
+ 0 comments Hello!
I'm learning Java, this solution was converted from @Jugad's Javascript solution, but I'm failing test cases 6 and 10. Can anyone help?
// Complete the countTriplets function below. static long countTriplets(List<Long> arr, long r) { //0. Initializations Map<Long, Long> singleCounts = new HashMap<>(); Map<Long, Long> pairCounts = new HashMap<>(); long triplets = 0; //1. Sort array ascending order Collections.sort(arr, Collections.reverseOrder()); //2. Iterate through sorted array for (Long num: arr) { // A. Count completed pairs if (pairCounts.get(num*r) != null) { triplets += pairCounts.get(num*r); } // B. Increment pair counts if needed if (singleCounts.get(num*r) != null) { pairCounts.merge(num, singleCounts.get(num*r), Long::sum); } // C. Increment single counts singleCounts.merge(num, Long.valueOf(1), Long::sum); } return triplets; }
+ 0 comments have to be the worst examples to put out there with no insight whatsoever on how inputs can be. also this question is more mathematics over "dictionaries and hashmaps"
+ 0 comments Wow, that took a while. "The ratio of any two consecutive terms in a geometric progression is the same".
def countTriplets(arr, r): ntuples = 0 div_r = defaultdict(lambda: 0) r_val = defaultdict(lambda: 0) for v in arr: ntuples += div_r[v/r] div_r[v] += r_val[v/r] r_val[v] += 1 return ntuples
Load more conversations
Sort 756 Discussions, By:
Please Login in order to post a comment