Count Pairs That Form a Complete Day I - 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: Valid pairs: (0,1) → 12+12=24, (3,4) → 24+24=48. Both sums are multiples of 24.
Example 2 — No Valid Pairs
$ Input: hours = [72,48,24,3]
Output: 3
💡 Note: Valid pairs: (0,1) → 72+48=120, (0,2) → 72+24=96, (1,2) → 48+24=72. All are multiples of 24.
Example 3 — Single Element
$ Input: hours = [1,2]
Output: 0
💡 Note: 1+2=3 is not a multiple of 24, so no valid pairs exist.

Constraints

  • 1 ≤ hours.length ≤ 100
  • 1 ≤ hours[i] ≤ 109

Visualization

Tap to expand
Count Pairs That Form a Complete Day INPUT hours array: 12 i=0 12 i=1 30 i=2 24 i=3 24 i=4 hours[i] % 24: 12 12 6 0 0 Complete Day Condition: (a + b) % 24 == 0 Need: r1 + r2 = 0 or 24 where r = hour % 24 12 + 12 = 24 [OK] 24 + 24 = 48 [OK] ALGORITHM STEPS 1 Create remainder count Hash map for hour%24 freq 2 For each hour value Find complement (24-r)%24 3 Add matching count pairs += count[complement] 4 Update count map count[r]++ for current Execution Trace: i h[i] r comp match pairs 0 12 12 12 0 0 1 12 12 12 1 1 2 30 6 18 0 1 3 24 0 0 0 1 4 24 0 0 1 2 FINAL RESULT Valid Pairs Found: Pair 1: (i=0, j=1) 12 + 12 = 24 = 1 day Pair 2: (i=3, j=4) 24 + 24 = 48 = 2 days Output: 2 [OK] 2 valid pairs found Time: O(n) Space: O(24) = O(1) Not valid: 12+30=42, 12+24=36 Key Insight: Two hours form a complete day when (h1 + h2) % 24 == 0. Using modular arithmetic, we only need to track remainders (hour % 24). For remainder r, we need complement (24-r) % 24. Hash map counts enable O(1) lookup for each element, making total time O(n) instead of O(n^2). TutorialsPoint - Count Pairs That Form a Complete Day I | Optimal Solution (Hash Map)
Asked in
Amazon 35 Microsoft 28 Google 22
34.8K 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