LeetCode 3185: Count Pairs That Form a Complete Day II Solution
Master LeetCode problem 3185 (Count Pairs That Form a Complete Day II), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
3185. Count Pairs That Form a Complete Day II
Problem Explanation
Explanation
To solve this problem, we can use a HashMap to store the frequencies of remainders when the sum of two hours is divided by 24. By iterating over the input array, we calculate the remainder for each element and check if the complement (24 - remainder) exists in the HashMap. If it does, we increment the count of valid pairs by the frequency of the complement in the HashMap. We also update the frequency of the current remainder in the HashMap.
Algorithm:
- Initialize a HashMap to store the frequency of remainders.
- Initialize a variable
countto store the total count of valid pairs. - Iterate over the input array
hours. - Calculate the remainder
remwhenhours[i]is divided by 24. - Check if the complement
(24 - rem)exists in the HashMap.- If it does, increment
countby the frequency of the complement in the HashMap.
- If it does, increment
- Update the frequency of the current remainder in the HashMap.
- Return the total count of valid pairs.
Time Complexity: O(N), where N is the number of elements in the input array hours.
Space Complexity: O(N), where N is the number of elements in the input array hours.
Solution Code
import java.util.HashMap;
class Solution {
public int countPairs(int[] hours) {
HashMap<Integer, Integer> remainderFreq = new HashMap<>();
int count = 0;
for (int hour : hours) {
int rem = hour % 24;
if (remainderFreq.containsKey(24 - rem)) {
count += remainderFreq.get(24 - rem);
}
remainderFreq.put(rem, remainderFreq.getOrDefault(rem, 0) + 1);
}
return count;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3185 (Count Pairs That Form a Complete Day II)?
This page provides optimized solutions for LeetCode problem 3185 (Count Pairs That Form a Complete Day II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 3185 (Count Pairs That Form a Complete Day II)?
The time complexity for LeetCode 3185 (Count Pairs That Form a Complete Day II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3185 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3185 in Java, C++, or Python.