Untitled

 avatar
unknown
plain_text
5 months ago
1.4 kB
6
Indexable
public static int getTripletCount(List<Integer> a, int d) {
        int n = a.size();
        int count = 0;

        // Convert list to array for faster access
        int[] arr = a.stream().mapToInt(Integer::intValue).toArray();

        // Count occurrences of remainders
        Map<Integer, Integer> remainderCount = new HashMap<>();
        for (int i = 0; i < n; i++) {
            int remainder = arr[i] % d;
            remainderCount.put(remainder, remainderCount.getOrDefault(remainder, 0) + 1);
        }

        // Iterate over all pairs and check if there's a valid third element
        for (int i = 0; i < n - 2; i++) {
            for (int j = i + 1; j < n - 1; j++) {
                // Calculate required remainder for the third element
                int currentSum = arr[i] + arr[j];
                int requiredRemainder = (d - (currentSum % d)) % d;

                // Providing that the element appears after j
                if (remainderCount.containsKey(requiredRemainder)) {
                    // Count how many such elements exist beyond the j-th element
                    count += remainderCount.get(requiredRemainder) 
                                - (arr[j] % d == requiredRemainder ? 1 : 0)
                                - (arr[i] % d == requiredRemainder ? 1 : 0);
                }
            }
        }

        return count / 2;  // Dividing by 2 to compensate for double counting
    }
Editor is loading...
Leave a Comment