Count Pairs That Form a Complete Day I Problem
#3184
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3184.
Given an integer array hours representing times in hours, return an integer denoting the number of pairs i, j where i < j and hours[i] + hours[j] forms a complete day.
A complete day is defined as a time duration that is an exact multiple of 24 hours.
For example, 1 day is 24 hours, 2 days is 48 hours, 3 days is 72 hours, and so on.
Example 1:
Input: hours = [12,12,30,24,24]
Output: 2
Explanation:
The pairs of indices that form a complete day are (0, 1) and (3, 4).
Example 2:
Input: hours = [72,48,24,3]
Output: 3
Explanation:
The pairs of indices that form a complete day are (0, 1), (0, 2), and (1, 2).
Constraints:
1 <= hours.length <= 1001 <= hours[i] <= 10^9
Solution
Approach: Counting
Only the hour modulo 24 matters. Keep an array cnt of 24 counters. For each hour x, the partner that makes a multiple of 24 has remainder (24 - x % 24) % 24; add the number of earlier hours with that remainder to the answer, then count x % 24. Each pair is counted once, when its later element is processed.
Complexity: O(n) time and O(1) space (24 counters).
from collections import Counter
class Solution:
def countCompleteDayPairs(self, hours: List[int]) -> int:
cnt = Counter()
ans = 0
for x in hours:
ans += cnt[(24 - (x % 24)) % 24]
cnt[x % 24] += 1
return ans