Four Sum Count
In Four Sum Count, you’re given four integer arrays (A, B, C, D). Your task is to return the total number of tuples (i,j,k,l) such that their sum equals zero. This challenge tests your ability to handle complex combinations with maximum efficiency!
The "secret sauce" here is a clever Hash Map to avoid a slow brute-force approach. Instead of checking every combination (which would be O(N⁴)), you split the problem in half. First, calculate all possible sums of pairs from A and B and store them in a map with their frequency. Then, calculate sums from C and D and ask your map: "Do I have a previous sum that, when added to this one, equals zero?" This turns a massive problem into a lightning-fast O(N²) solution! It’s a brilliant leap in thinking that teaches you how to "divide and conquer" complexity using memory strategically. Even millions of combinations become easy to handle!
Keep the algorithm focused on one clear invariant and update path so correctness is easy to verify from left to right. This reduces accidental branching errors and helps ensure the final output stays consistent with the problem contract across random and adversarial test shapes.
Examples
Two tuples satisfy sum zero.
Only one tuple and it sums to zero.
No tuple sums to zero.
Algorithm Flow

Best Answers
import java.util.*;
class Solution {
public int four_sum_count(int[] A, int[] B, int[] C, int[] D) {
Map<Integer, Integer> ab = new HashMap<>();
for (int a : A) {
for (int b : B) {
int s = a + b;
ab.put(s, ab.getOrDefault(s, 0) + 1);
}
}
int ans = 0;
for (int c : C) {
for (int d : D) {
ans += ab.getOrDefault(-(c + d), 0);
}
}
return ans;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this problem.
