Problem Description
Given an array of integers representing hours, count the number of pairs (i, j) with i < j such that the sum hours[i] + hours[j] is an exact multiple of 24, forming a complete day.
Key Insights
- Convert each hour to its remainder modulo 24.
- A valid pair is formed when the sum of two remainders is 0 modulo 24.
- Group numbers by their remainder to efficiently count complementary pairs.
- Special handling is needed for remainders 0 and 12, as they pair with themselves.
Space and Time Complexity
Time Complexity: O(n), where n is the number of hours.
Space Complexity: O(1), as the frequency array size is fixed (24).
Solution
We first compute the remainder of each element in the array when divided by 24 and count the frequency using a fixed-size array or hash table. For any remainder r, its complement that sums to a multiple of 24 is (24 - r) % 24. For remainders that pair with themselves (0 and 12), we use the combination formula (n * (n - 1)) / 2 to count valid pairs. For other remainders, we multiply the frequency of r with that of (24 - r) while making sure each complementary pair is only counted once.