Count Pairs That Form a Complete Day II - Counting Modulo Values [JS]
Solution: Counting Modulo Values
Keep a running count of occurances of each hour % 24
.
For each hour, we need to find the other modulo value needed to make up a multiple of 24
: 24 - (hour % 24)
Return the total sum of count[(24 - (hour % 24)) % 24]
.
n = length of hours
Time Complexity: O(n)
Space Complexity: O(24)
= O(1)
var countCompleteDayPairs = function(hours) {
let count = Array(24).fill(0), pairs = 0;
for (let hour of hours) {
pairs += count[(24 - (hour % 24)) % 24];
count[hour % 24]++;
}
return pairs;
};
Comments
Post a Comment