702729. Pairs which are Divisible by 4
Pairs which are Divisible by 4
Summary
Given an array of integers, we need to find all pairs that can be divided by 4. The problem requires us to count the number of such pairs in the array.
This problem involves arrays and data structures, specifically hash tables. We will use a hashmap to store the frequency of each element in the array and then iterate through the map to find the pairs that are divisible by 4.
Detailed Explanation
To solve this problem, we can start by initializing an empty hashmap, freq. Then, we iterate over the input array and update the frequency of each element in the freq map. Next, we initialize a variable count to store the number of pairs that are divisible by 4.
We then iterate through the freq map and for each key-value pair, we check if the value is greater than or equal to 2 (since a pair requires at least two occurrences). If it is, we add the product of the key and the value divided by 4 to the count. This ensures that we count all pairs that are divisible by 4.
Here's the step-by-step breakdown:
- Initialize an empty hashmap,
freq. - Iterate over the input array and update the frequency of each element in the
freqmap. - Initialize a variable
countto store the number of pairs that are divisible by 4. - Iterate through the
freqmap and for each key-value pair:- Check if the value is greater than or equal to 2.
- If it is, add the product of the key and the value divided by 4 to the
count.
- Return the
count.
Time Complexity: O(n), where n is the size of the input array.
Space Complexity: O(n), where n is the size of the input array (for storing the frequency map).
Optimized Solutions
Java
import java.util.HashMap;
import java.util.Map;
public int pairsDivisibleBy4(int[] arr) {
Map<Integer, Integer> freq = new HashMap<>();
int count = 0;
for (int num : arr) {
freq.put(num, freq.getOrDefault(num, 0) + 1);
}
for (Map.Entry<Integer, Integer> entry : freq.entrySet()) {
if (entry.getValue() >= 2) {
count += Math.min(entry.getKey(), entry.getValue()) / 4;
}
}
return count;
}