Count Pairs That Form a Complete Day II - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: hours = [12,12,30,24,24]
Output: 2
💡 Note: The valid pairs are (0,1) where 12+12=24 and (3,4) where 24+24=48. Both sums are multiples of 24.
Example 2 — Mixed Remainders
$ Input: hours = [72,48,24,3]
Output: 3
💡 Note: Valid pairs: (0,1): 72+48=120=24×5, (0,2): 72+24=96=24×4, (1,2): 48+24=72=24×3. All three pairs sum to multiples of 24.
Example 3 — No Valid Pairs
$ Input: hours = [1,2,3,4]
Output: 0
💡 Note: No pair sums to a multiple of 24: 1+2=3, 1+3=4, 1+4=5, 2+3=5, 2+4=6, 3+4=7. None are divisible by 24.

Constraints

  • 1 ≤ hours.length ≤ 5 × 105
  • 1 ≤ hours[i] ≤ 109

Visualization

Tap to expand
Count Pairs That Form a Complete Day II INPUT hours array (5 elements) 12 i=0 12 i=1 30 i=2 24 i=3 24 i=4 Remainders (mod 24) 12 12 6 0 0 Complete day condition: (a + b) % 24 == 0 Valid Pairs (0,1): 12+12=24 [OK] (3,4): 24+24=48 [OK] (2,x): 30+?=24k [None] ALGORITHM STEPS 1 Init Count Array count[24] tracks remainders 2 Iterate Array For each hour, get r = h%24 3 Find Complement comp = (24 - r) % 24 4 Count and Update pairs += count[comp] count[r]++ Count Array State r=0 2 r=6 1 r=12 2 others=0 Time: O(n) | Space: O(24) One pass through array FINAL RESULT Iteration Trace i=0: r=12, comp=12, pairs=0 i=1: r=12, comp=12, pairs=1 i=2: r=6, comp=18, pairs=1 i=3: r=0, comp=0, pairs=1 i=4: r=0, comp=0, pairs=2 Valid Pairs Found Pair 1: (0,1) = 24 Pair 2: (3,4) = 48 Output 2 2 pairs form complete days (multiples of 24 hours) Key Insight: Two numbers sum to a multiple of 24 if and only if their remainders (mod 24) are complements. For remainder r, we need complement (24-r)%24. Use a count array to track seen remainders, achieving O(n) time by counting matching complements before updating the current remainder count. TutorialsPoint - Count Pairs That Form a Complete Day II | Optimal Solution (Hash Map / Counting)
Asked in
Amazon 15 Microsoft 12 Google 8
23.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen