Count Pairs That Form a Complete Day II - Problem

You're given an integer array hours representing time durations in hours. Your task is to find 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:

  • 24 hours = 1 complete day
  • 48 hours = 2 complete days
  • 72 hours = 3 complete days

Key insight: Two numbers sum to a multiple of 24 if and only if the sum of their remainders when divided by 24 equals 0 or 24.

Example: If hours = [12, 12, 30, 24, 24], the pairs (0,1), (3,4) form complete days because 12+12=24 and 24+24=48.

Input & Output

example_1.py โ€” Basic pairing
$ Input: [12, 12, 30, 24, 24]
โ€บ Output: 2
๐Ÿ’ก Note: Pair (0,1): hours[0] + hours[1] = 12 + 12 = 24 (1 complete day). Pair (3,4): hours[3] + hours[4] = 24 + 24 = 48 (2 complete days). Total: 2 pairs.
example_2.py โ€” No valid pairs
$ Input: [72, 48, 24, 3]
โ€บ Output: 3
๐Ÿ’ก Note: All pairs: (0,1)=120hrs, (0,2)=96hrs, (0,3)=75hrs, (1,2)=72hrs, (1,3)=51hrs, (2,3)=27hrs. Valid pairs: (0,1), (0,2), (1,2) as 120, 96, and 72 are all multiples of 24.
example_3.py โ€” Single element
$ Input: [1, 23, 25, 47]
โ€บ Output: 2
๐Ÿ’ก Note: Pair (0,1): 1 + 23 = 24. Pair (2,3): 25 + 47 = 72 (which is 24ร—3). Both form complete days.

Visualization

Tap to expand
0/246181224-Hour Clock Visualization6+18=24 โœ“Key Insight:โ€ข Hour 30 โ†’ Position 6 (30%24=6)โ€ข Hour 42 โ†’ Position 18 (42%24=18)โ€ข Positions 6+18=24 โ†’ Valid pair!Time: O(n), Space: O(1)
Understanding the Visualization
1
Map to clock positions
Convert each hour to its position on 24-hour clock (hour % 24)
2
Find complements
For position X, find how many previous elements were at position (24-X)%24
3
Count pairs
Each complement match represents a valid pair that sums to multiple of 24
Key Takeaway
๐ŸŽฏ Key Insight: Only remainders modulo 24 matter! This reduces the problem to counting complementary remainders in a fixed-size array.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through array, with O(1) operations per element

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Fixed-size array of 24 elements regardless of input size

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค hours.length โ‰ค 105
  • 1 โ‰ค hours[i] โ‰ค 109
  • Note: This is the 'II' version, optimized for larger constraints
Asked in
Google 42 Amazon 38 Meta 35 Microsoft 28 Apple 22
52.3K Views
Medium-High Frequency
~18 min Avg. Time
1.8K 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