Count Triplets

  • [deleted]
    + 1 comment

    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;
        }