Count Triplets

  • + 0 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]++; } }

    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;
    

    }