Leetcode 3184. Count Pairs That Form a Complete Day I
Given an array of integers arr
and an integer k
, find the number of unique pairs (i, j)
(where i < j
) such that the sum of arr[i]
and arr[j]
forms a “complete day”. A “complete day” occurs when the sum of two elements is divisible by k
.
arr = [1, 2, 3, 4, 5]
, k = 3
4
k
.k
.r
and k-r
, compute the number of valid pairs.0
or k/2
(if k
is even).Here’s the Java implementation of the optimized approach:
import java.util.HashMap;
import java.util.Map;
public class CompleteDayPairs {
public int countPairs(int[] arr, int k) {
// Map to store remainder frequencies
Map<Integer, Integer> remainderCount = new HashMap<>();
// Populate the remainder count
for (int num : arr) {
int remainder = (num % k + k) % k; // Handle negative numbers
remainderCount.put(remainder, remainderCount.getOrDefault(remainder, 0) + 1);
}
int count = 0;
// Iterate through the remainder keys
for (int rem : remainderCount.keySet()) {
int complement = (k - rem) % k;
// Special case: remainder 0 can only pair with itself
if (rem == 0 || rem == complement) {
int freq = remainderCount.get(rem);
count += (freq * (freq - 1)) / 2; // Combination formula: nC2 = n*(n-1)/2
} else if (rem > complement) {
// Count pairs rem and complement
count += remainderCount.get(rem) * remainderCount.getOrDefault(complement, 0);
}
}
return count;
}
public static void main(String[] args) {
CompleteDayPairs solution = new CompleteDayPairs();
int[] arr = {1, 2, 3, 4, 5};
int k = 3;
int result = solution.countPairs(arr, k);
System.out.println("Number of pairs: " + result); // Output: 4
}
}
k
different remainders.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?