Count Pairs That Form a Complete Day II Solution In C++/Java/Python/JS
Problem Description
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.

Example
Example 1:
Input: hours = [12,12,30,24,24]
Output: 2
Explanation: The pairs of indices that form a complete day are (0, 1) and (3, 4).
Example 2:
Input: hours = [72,48,24,3]
Output: 3
Explanation: The pairs of indices that form a complete day are (0, 1), (0, 2), and (1, 2).
Constraints
- 1 <= hours.length <= 5 * 10^5
- 1 <= hours[i] <= 10^9
Let's tackle the problem “Count Pairs That Form a Complete Day II” step by step. We'll start by understanding the most intuitive solution and then work our way toward a more optimized approach, if one exists. So, grab a pen and paper, and let's break down the algorithm together!
Brute Force Approach
Intuition
If we break down this problem, we are given an array hours consisting of positive integers.
The task is to find the number of pairs (i, j) such that:
- i < j, and
- (hours[i] + hours[j]) % 24 == 0
Now, if we observe carefully, we realize that the challenge is to find all unique pairs where the sum of the two elements is divisible by 24.
So, the first idea that comes to our mind is:
Why don’t we try checking every possible pair (i, j) and for each one, verify if the sum is divisible by 24?
This makes sense because:
- A brute force solution can explore all such pairs by picking every starting index i and pairing it with every index j > i.
- During this process, if the sum of the two elements is divisible by 24, we count that pair.
- For every valid pair found, we increment our counter.
- In the end, we return the total number of such valid pairs.
Let’s illustrate this with an example:
hours = [8, 16, 24, 3]
We start from index 0:
- Pair: [8, 16] → 8 + 16 = 24 → divisible by 24 → count = 1
- Pair: [8, 24] → 8 + 24 = 32 → not divisible by 24
- Pair: [8, 3] → 8 + 3 = 11 → not divisible by 24
Start from index 1:
- Pair: [16, 24] → 16 + 24 = 40 → not divisible by 24
- Pair: [16, 3] → 16 + 3 = 19 → not divisible by 24
Start from index 2:
- Pair: [24, 3] → 24 + 3 = 27 → not divisible by 24
So, total valid pairs = 1
But there is one important edge case we must handle:
What if the array contains all values such that each pair adds up to a multiple of 24?
Example:
hours = [24, 0, 48]
In this case:
- (24 + 0 = 24) → divisible by 24
- (24 + 48 = 72) → divisible by 24
- (0 + 48 = 48) → divisible by 24
→ All pairs are valid → total = 3
Therefore:
Even if elements are themselves divisible by 24 or zero, we must still verify all pair sums, not just look at individual values.
The brute force will handle this naturally by checking every pair's sum.
We must ensure we don’t skip any pairs and only count those that satisfy the exact modulo condition.
Count Pairs That Form a Complete Day II Algorithm
Step 1: Initialize Variables
- Create an integer ans = 0 to store the final count of valid pairs.
- Create an integer n = hours.length to store the size of the array.
Step 2: Try Every Starting Index
- Loop through each index i from 0 to n - 1:
- For each i, we’ll try pairing it with all elements after it to form (i, j) pairs.
Step 3: Try Every Ending Index After i
- Loop through each index j from i + 1 to n - 1:
- Check if the sum of hours[i] + hours[j] is divisible by 24:
- If (hours[i] + hours[j]) % 24 == 0, it forms a valid complete day pair.
- Increment ans by 1.
- Check if the sum of hours[i] + hours[j] is divisible by 24:
Step 4: Return the Result
- After checking all pairs in the array:
- Return ans as the total number of valid (i, j) pairs where i < j and (hours[i] + hours[j]) % 24 == 0.
Dry-Run
Input: hours = [8, 16, 24, 3]
Step 1: Initialize Variables
- ans = 0 (to store the number of valid pairs)
- n = hours.length = 4
Step 2: Try Every Starting IndexFirst Iteration (i = 0)
- Try all j > i (j from 1 to 3)
- j = 1 → hours[0] + hours[1] = 8 + 16 = 24
→ 24 % 24 == 0 → valid pair → ans = 1 - j = 2 → 8 + 24 = 32
→ 32 % 24 = 8 → not valid - j = 3 → 8 + 3 = 11
→ 11 % 24 = 11 → not valid
Result from i = 0 → 1 valid pair found → ans = 1
Second Iteration (i = 1)
- Try j = 2 and j = 3
- j = 2 → 16 + 24 = 40
→ 40 % 24 = 16 → not valid - j = 3 → 16 + 3 = 19
→ 19 % 24 = 19 → not valid
Result from i = 1 → 0 valid pairs → ans = 1
Third Iteration (i = 2)
- Try j = 3
- j = 3 → 24 + 3 = 27
→ 27 % 24 = 3 → not valid
Result from i = 2 → 0 valid pairs → ans = 1
Fourth Iteration (i = 3)
- No j > i exists → nothing to check
Result from i = 3 → 0 valid pairs → ans = 1
Final Step: Return the Result
- After checking all pairs, return ans = 1
Final Output: 1
Only the pair (0, 1) → [8, 16] forms a complete day (i.e., sum divisible by 24).
Count Pairs That Form a Complete Day II Solution
Now let's check out the Count Pairs That Form a Complete Day II code in C++ , Java, Python and JavaScript.
Count Pairs That Form a Complete Day II Code in all Languages.
1. Count Pairs That Form a Complete Day II Solution in C++ Try on Compiler
#include <iostream>
#include <vector>
using namespace std;
// Function to count valid pairs
int countCompleteDayPairs(vector<int>& hours) {
int ans = 0;
int n = hours.size();
// Check all pairs (i, j) where i < j
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// If sum is divisible by 24, count it
if ((hours[i] + hours[j]) % 24 == 0) {
ans++;
}
}
}
return ans;
}
int main() {
int n;
cin >> n; // Read number of elements
vector<int> hours(n);
for (int i = 0; i < n; i++) {
cin >> hours[i]; // Read elements
}
cout << countCompleteDayPairs(hours); // Print result
return 0;
}
2. Count Pairs That Form a Complete Day II Solution in Java Try on Compiler
import java.util.*;
public class Main {
// Function to count valid pairs
public static int countCompleteDayPairs(int[] hours) {
int ans = 0;
int n = hours.length;
// Check all (i, j) pairs where i < j
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// Check if their sum is divisible by 24
if ((hours[i] + hours[j]) % 24 == 0) {
ans++;
}
}
}
return ans;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); // Read number of elements
int[] hours = new int[n];
for (int i = 0; i < n; i++) {
hours[i] = sc.nextInt(); // Read each hour
}
System.out.print(countCompleteDayPairs(hours)); // Print result
}
}
3. Count Pairs That Form a Complete Day II Solution in Python Try on Compiler
def count_complete_day_pairs(hours):
ans = 0
n = len(hours)
# Try all (i, j) pairs with i < j
for i in range(n):
for j in range(i + 1, n):
# Check if the sum is divisible by 24
if (hours[i] + hours[j]) % 24 == 0:
ans += 1
return ans
if __name__ == "__main__":
n = int(input()) # Read number of elements
hours = list(map(int, input().split())) # Read the array
print(count_complete_day_pairs(hours)) # Output result
4. Count Pairs That Form a Complete Day II Solution in JavaScript Try on Compiler
function countCompleteDayPairs(hours) {
let ans = 0;
let n = hours.length;
// Try all pairs (i, j) with i < j
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
// Check if sum is divisible by 24
if ((hours[i] + hours[j]) % 24 === 0) {
ans++;
}
}
}
return ans;
}
// Main input/output handling
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let input = [];
rl.on("line", function(line) {
input.push(line.trim());
if (input.length === 2) {
let n = parseInt(input[0]);
let hours = input[1].split(" ").map(Number);
console.log(countCompleteDayPairs(hours)); // Output result
rl.close();
}
});
Count Pairs That Form a Complete Day II Complexity Analysis
Time Complexity: O(n^2)
Initial Input Reading Loop: O(n)
- The code reads n elements from input (e.g., via loop or split/map).
- This takes linear time with respect to the size of the array.
- Time: O(n)
Outer Loop (Try Every First Index i): O(n)
- We loop over each index i from 0 to n - 1.
- So the outer loop runs n times.
- Time: O(n)
Inner Loop (Try Every Second Index j > i): O(n)
- For each index i, we loop j from i + 1 to n - 1.
- In the worst case, this loop also runs up to n times.
- So for each outer iteration, inner loop contributes up to n - 1 operations.
- Time: O(n)
Total Work Done: O(n²)
- Outer loop runs n times
- Inner loop runs up to n times each time
- So total time = O(n) * O(n) = O(n²)
- No early stopping or optimizations are applied in brute force.
Final Time Complexity: O(n²)
Space Complexity: O(n)
Auxiliary Space Complexity: O(1)
This refers to any extra space used by the algorithm, excluding the input and output space.
In this approach, we use:
- A few scalar variables: ans, n, i, and j
- No additional data structures such as lists, sets, or maps are used during the computation
Since no dynamic structures are created and only fixed-size variables are maintained,
The auxiliary space used is constant → O(1)
Input Space: O(n)
The input array hours contains n integers.
It is stored as a Python list, which occupies linear space.
Input Space: O(n)
Output Space: O(1)
The function returns a single integer value — the total number of valid pairs.
This takes constant space.
Output Space: O(1)
The
Combining all the components:
- Input array: O(n)
- Output value: O(1)
- Extra space used (variables): O(1)
Total Space Complexity = O(n) + O(1) + O(1) = O(n)
Optimal Approach
Intuition
In the brute force approach, we iterate over all pairs (i, j) where i < j and check if the sum of hours[i] and hours[j] is divisible by 24. This involves two nested loops: the outer loop fixes the first element, and the inner loop tries every second element that comes after it. For each such pair, we check if (hours[i] + hours[j]) % 24 == 0. If it is, we count the pair.
While this approach is simple and easy to understand, it is inefficient — the time complexity is O(n²) because we are examining all possible pairs in the array. For large arrays, this quickly becomes too slow to run within time limits.
But let’s take a closer look: What are we really doing when checking (hours[i] + hours[j]) % 24 == 0? We're trying to find two numbers whose sum is a multiple of 24. This can be reframed as: if one number leaves a remainder r1 when divided by 24, we need another number with a remainder r2 such that r1 + r2 ≡ 0 (mod 24). In other words, r2 = (24 - r1) % 24. This mathematical insight lets us avoid recomputing every possible pair.
Here’s the key idea: instead of checking all pairs, we can process each element once and use a HashMap to store the count of each remainder modulo 24 we've seen so far. While iterating through the array, for each number we calculate its remainder rem = hours[i] % 24, and we determine its complement comp = (24 - rem) % 24. This complement is the exact value we’d need from a previously seen number to form a valid pair. If this complement already exists in our map, then we can form as many valid pairs as the count of comp.
After checking for a valid pair, we then record the current remainder rem
in the map by incrementing its count. This way, all future elements can pair with it if they need this remainder. Since each element is processed once and all operations (map lookup, update) are average O(1), the total time complexity is reduced to O(n).
This HashMap-based approach is significantly more efficient and easily scales for large inputs, while also being simple to implement once the modular arithmetic insight is clear.
Count Pairs That Form a Complete Day II Algorithm
Step 1: Initialize Variables
- Create an integer ans = 0 (or long, if needed) to store the final count of valid pairs.
- Create a HashMap map to store frequencies of remainders when elements are taken modulo 24.
Step 2: Loop Through Each Element in the Array
- For each element h in the array hours:
- Compute the remainder rem = h % 24.
- Compute the complement comp = (24 - rem) % 24.
This is the value that, when added to rem, makes the total divisible by 24.
Step 3: Check for Complement in the Map
- If comp exists in the map, it means we’ve seen that many elements earlier
that can pair with the current h to form a valid complete day. - Add map[comp] to ans.
Step 4: Add Current Remainder to the Map
- After checking for a pair, add or update the current rem in the map:
- map[rem] = map.getOrDefault(rem, 0) + 1
Step 5: Return the Result
- After processing all elements in the array:
- Return ans as the total number of valid (i, j) pairs
such that i < j and (hours[i] + hours[j]) % 24 == 0.
- Return ans as the total number of valid (i, j) pairs

Dry-Run
Input: hours = [8, 16, 24, 3]
Step 1: Initialize Variables
- ans = 0
- map = {} (HashMap to store remainder frequencies)
Step 2: Traverse the Arrayv
First Iteration (i = 0)
- hours[0] = 8
- rem = 8 % 24 = 8
- comp = (24 - 8) % 24 = 16
- comp 16 not in map → no pairs found
- Add rem 8 to map → map = {8: 1}
- ans = 0
Second Iteration (i = 1)
- hours[1] = 16
- rem = 16 % 24 = 16
- comp = (24 - 16) % 24 = 8
- comp 8 is in map → map[8] = 1 → valid 1 pair
- Add to ans → ans = 1
- Add rem 16 to map → map = {8: 1, 16: 1}
Third Iteration (i = 2)
- hours[2] = 24
- rem = 24 % 24 = 0
- comp = (24 - 0) % 24 = 0
- comp 0 not in map → no pairs found
- Add rem 0 to map → map = {0: 1, 8: 1, 16: 1}
- ans = 1
Fourth Iteration (i = 3)
- hours[3] = 3
- rem = 3 % 24 = 3
- comp = (24 - 3) % 24 = 21
- comp 21 not in map → no pairs found
- Add rem 3 to map → map = {0: 1, 3: 1, 8: 1, 16: 1}
- ans = 1
Step 3: End of Array Reached
- Final index = 3 → loop ends
Step 4: Return the Result
- Return ans = 1
Final Output: 1
Only one valid pair exists: (8, 16) → sum is 24 → divisible by 24.
Count Pairs That Form a Complete Day II Solution
Now let's check out the Count Pairs That Form a Complete Day II code in C++ , Java, Python and JavaScript.
Count Pairs That Form a Complete Day II Code in all Languages.
1. Count Pairs That Form a Complete Day II Solution in C++ Try on Compiler
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
// Function to count valid complete day pairs
long countCompleteDayPairs(const vector<int>& hours) {
unordered_map<int, int> map;
long ans = 0;
for (int h : hours) {
int rem = h % 24; // Current remainder mod 24
int comp = (24 - rem) % 24; // Complement to make sum % 24 == 0
if (map.find(comp) != map.end()) {
ans += map[comp]; // Count valid pairs using complement
}
map[rem]++; // Store current remainder in map
}
return ans;
}
int main() {
int n;
cin >> n; // Read array size
vector<int> hours(n);
for (int i = 0; i < n; i++) {
cin >> hours[i]; // Read array elements
}
cout << countCompleteDayPairs(hours); // Output result
return 0;
}
2. Count Pairs That Form a Complete Day II Solution in Java Try on Compiler
import java.util.*;
public class Main {
// Function to count valid pairs whose sum is divisible by 24
public static long countCompleteDayPairs(int[] hours) {
Map<Integer, Integer> map = new HashMap<>();
long ans = 0;
for (int h : hours) {
int rem = h % 24; // Current value modulo 24
int comp = (24 - rem) % 24; // Complement remainder
if (map.containsKey(comp)) {
ans += map.get(comp); // Add number of valid complements
}
map.put(rem, map.getOrDefault(rem, 0) + 1); // Update remainder count
}
return ans;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); // Read number of elements
int[] hours = new int[n];
for (int i = 0; i < n; i++) {
hours[i] = sc.nextInt(); // Read array values
}
System.out.print(countCompleteDayPairs(hours)); // Output the result
}
}
3. Count Pairs That Form a Complete Day II Solution in Python Try on Compiler
def count_complete_day_pairs(hours):
rem_count = {}
ans = 0
for h in hours:
rem = h % 24 # Remainder when divided by 24
comp = (24 - rem) % 24 # Complement that makes sum % 24 == 0
ans += rem_count.get(comp, 0) # Add pairs with valid complements
rem_count[rem] = rem_count.get(rem, 0) + 1 # Update remainder count
return ans
if __name__ == "__main__":
n = int(input()) # Read array size
hours = list(map(int, input().split())) # Read elements
print(count_complete_day_pairs(hours)) # Output result
4. Count Pairs That Form a Complete Day II Solution in JavaScript Try on Compiler
function countCompleteDayPairs(hours) {
const map = new Map();
let ans = 0;
for (let h of hours) {
const rem = h % 24; // Remainder mod 24
const comp = (24 - rem) % 24; // Complement remainder
if (map.has(comp)) {
ans += map.get(comp); // Count valid pairs
}
map.set(rem, (map.get(rem) || 0) + 1); // Update map with current remainder
}
return ans;
}
// Read input and output result
const readline = require("readline");
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
let input = [];
rl.on("line", function (line) {
input.push(line.trim());
if (input.length === 2) {
const n = parseInt(input[0]);
const hours = input[1].split(" ").map(Number);
console.log(countCompleteDayPairs(hours)); // Output result
rl.close();
}
});
Count Pairs That Form a Complete Day II Complexity Analysis
Time Complexity: O(n)
Initial Input Reading Loop: O(n)
- The code reads n elements from the input.
- This involves reading the array and possibly parsing it.
- Time: O(n)
Single Pass Through the Array: O(n)
- We loop over each element h in the array hours.
- For each element, we:
- Compute rem = h % 24 → O(1)
- Compute comp = (24 - rem) % 24 → O(1)
- Check if comp exists in the HashMap → O(1) on average
- Update the HashMap count for rem → O(1) on average
- All of these operations are constant time per element.
Total Work Done: O(n)
- We process each element exactly once.
- HashMap lookups and inserts are O(1) on average.
- There are no nested loops or repeated processing.
Final Time Complexity: O(n)
Space Complexity: O(n)
Auxiliary Space Complexity: O(1)
This refers to extra space used by the algorithm, excluding the input and output.
In this approach, we use:
- A HashMap to store counts of remainders mod 24
- At most, the HashMap will store 24 unique keys (0 through 23)
- A few scalar variables like ans, rem, comp
Since the HashMap size is independent of n and bounded by 24,
The auxiliary space used is constant → O(1)
Input Space: O(n)
The input array hours contains n integers → occupies linear space
Input Space: O(n)
Output Space: O(1)
The function returns a single integer value (the number of valid complete day pairs).
This result takes constant space.
Output Space: O(1)
Total Space Complexity: O(n)
Combining all the components:
- Input array: O(n)
- Output value: O(1)
- Extra space used (HashMap + variables): O(1)
Total Space Complexity = O(n) + O(1) + O(1) = O(n)
Similar Problems
You are given a list of songs where the ith song has a duration of time[i] seconds.
Return the number of pairs of songs for which their total duration in seconds is divisible by 60. Formally, we want the number of indices i, j such that i < j with (time[i] + time[j]) % 60 == 0.
Given an array of integers arr of even length n and an integer k.
We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k.
Return true If you can find a way to do that or false otherwise.