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.

Here's a simple javascript solution. We basically have two hashmaps - prev and next to keep track of items we've visited and ones that we still need to visit. Each time we find a geomatric set, we compute the sum based on the number of repeating characters and add it to the total counter. I derived the solution from the following youtube explanation.

function countTriplets(arr, r) {
if(arr.length < 3) {
return 0;
}
const prev = {};
const next = {};
for(let x of arr){
if(!next[x]) {
next[x] = 1;
} else {
next[x]++;
}
}

let current = null;
let counter = 0;
//a/r, a, a*r
for(let i = 0; i < arr.length; i++) {
current = arr[i];
const left = current/r;
const right = current * r;
next[current]--;
let sum = 1;
if(prev[left] && next[right]) {
sum *= prev[left]
sum *= next[right]
counter += sum;
}
if(!prev[current]) {
prev[current] = 1;
} else {
prev[current]++;
}
}
return counter;

}

Cookie support is required to access HackerRank

Seems like cookies are disabled on this browser, please enable them to open this website

## Count Triplets

You are viewing a single comment's thread. Return to all comments â†’

Here's a simple javascript solution. We basically have two hashmaps - prev and next to keep track of items we've visited and ones that we still need to visit. Each time we find a geomatric set, we compute the sum based on the number of repeating characters and add it to the total counter. I derived the solution from the following youtube explanation.

https://www.youtube.com/watch?v=7YKr0ELmam4

function countTriplets(arr, r) { if(arr.length < 3) { return 0; } const prev = {}; const next = {}; for(let x of arr){ if(!next[x]) { next[x] = 1;

} else { next[x]++; } }

}