Given four lists A, B, C, and D of integer values, compute how many tuples (i, j, k, l) there are such that:
To clarify, you need to find the number of distinct tuples that sum up to zero where each element of the tuple comes from one of the four lists.
Given:
A = [1, 2]
B = [-2, -1]
C = [-1, 2]
D = [0, 2]
Output:
2
Explanation: The tuples are (0, 0, 0, 1) and (1, 1, 0, 0).
We’ll employ a hashmap (unordered_map) to count how often each sum of pairs from lists A and B appears. Then, we’ll iterate over pairs from lists C and D to check how many pairs match with the required sum to reach zero.
This way, rather than using a brute force algorithm which would be O(n^4), we reduce it to O(n^2) in terms of both time and space complexity.
#include <vector>
#include <unordered_map>
class Solution {
public:
int fourSumCount(std::vector<int>& A, std::vector<int>& B, std::vector<int>& C, std::vector<int>& D) {
std::unordered_map<int, int> sumAB;
// Store sums of pairs from A and B
for (int a : A) {
for (int b : B) {
sumAB[a + b]++;
}
}
int count = 0;
// Find complements in pairs from C and D
for (int c : C) {
for (int d : D) {
int target = -(c + d);
if (sumAB.find(target) != sumAB.end()) {
count += sumAB[target];
}
}
}
return count;
}
};
This approach effectively balances between time and space efficiency to handle the problem within reasonable limits.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?