#3185

Count Pairs That Form a Complete Day II

Medium
ArrayHash TableCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a hash map to count occurrences of remainders when each hour is divided by 24. This allows us to efficiently find pairs that sum to a multiple of 24 without checking every combination.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a hash map to count occurrences of each remainder when hours[i] is divided by 24.
  2. 2Step 2: For each hour, calculate the required complement remainder (24 - (current remainder) % 24) to form a complete day.
  3. 3Step 3: For each hour, add the count of the complement remainder from the hash map to the result.
  4. 4Step 4: Update the hash map with the current hour's remainder.
solution.py11 lines
1# Full working Python code
2
3def countPairs(hours):
4    count = 0
5    remainder_count = {}
6    for hour in hours:
7        remainder = hour % 24
8        complement = (24 - remainder) % 24
9        count += remainder_count.get(complement, 0)
10        remainder_count[remainder] = remainder_count.get(remainder, 0) + 1
11    return count

Complexity note: The time complexity is O(n) because we only traverse the array once. The space complexity is O(n) due to the hash map storing counts of remainders.

  • 1Pairs that sum to a multiple of 24 can be efficiently found using remainders.
  • 2Using a hash map allows us to count occurrences and find complements in constant time.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.