Triple sum

  • + 0 comments

    Used set to remove duplicates and create order. Put data back into vectors to retrieve indices for upper bound checks.

    // Complete the triplets function below.
    long triplets(vector<int> a, vector<int> b, vector<int> c) {
        long result = 0;
        std::set<int> setA{a.begin(), a.end()};
        std::set<int> setB{b.begin(), b.end()};
        std::set<int> setC{c.begin(), c.end()};
        
        std::vector<int> orderedA {setA.begin(), setA.end()};
        std::vector<int> orderedC {setC.begin(), setC.end()};
        
        for (const auto& itemB : setB)
        {
            auto idxA = std::upper_bound(orderedA.begin(), orderedA.end(), itemB);
            auto idxC = std::upper_bound(orderedC.begin(), orderedC.end(), itemB);
            auto aDiff = idxA - orderedA.begin();
            auto cDiff = idxC - orderedC.begin();
            result += aDiff * cDiff;
        }
        
        return result;
    }