Count Triplets

  • + 0 comments

    thnks for explanation here's the code in c++ if anyone interested: hard time struck in defining a map with pair as a key tho ; }

    struct pair_hash
    {
            template <class T1, class T2>
            std::size_t operator() (const std::pair<T1, T2> &pair) const
            {
                    return std::hash<T1>()(pair.first) ^ std::hash<T2>()(pair.second);
            }
    };
    
    // Complete the countTriplets function below.
    long countTriplets(vector<long> arr, long r) {
            unordered_map<int, long> freq;
            long nxt,thrd;
            long count=0;
    
            // store 2 and 3 part of triplet as key
            unordered_map<pair<int, int> , long, pair_hash > pairs; 
    
            for(auto i=arr.rbegin(); i!=arr.rend(); i++ ){
                    nxt = *i * r;               //next element of triplet
    
                    thrd = *i *(r*r);           //3rd elemnt of the triplet
                    count+= pairs[{nxt,thrd}];    //if we get 1st element of the triplet
                    pairs[{*i, nxt}] += freq[nxt];   //if second elemnt of the triplet
    
                    freq[*i]++;                  //in case 3rd elemnt
            }
            return count;
    }