BudiBadu Logo

Four Sum Count

Hash Table Medium 2 views
Like0

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

Example 1
Input
A=[1,2], B=[-2,-1], C=[-1,2], D=[0,2]
Output
2
Explanation

Two tuples satisfy sum zero.

Example 2
Input
A=[0], B=[0], C=[0], D=[0]
Output
1
Explanation

Only one tuple and it sums to zero.

Example 3
Input
A=[1], B=[1], C=[1], D=[1]
Output
0
Explanation

No tuple sums to zero.

Algorithm Flow

Recommendation Algorithm Flow for Four Sum Count - Budibadu
Recommendation Algorithm Flow for Four Sum Count - Budibadu

Best Answers

java
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;
    }
}