Count Pairs That Form a Complete Day II - Counting Modulo Values [JS]

Description 

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 2424 - (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

Popular posts from this blog

Minimum Number of Operations to Sort a Binary Tree by Level - BFS & Cycle Counting Explained [JS]

Beautiful Towers II - Monotonic Increasing Stack [JS]

Reschedule Meetings for Maximum Free Time I - Sliding Window - Constant Space [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]