1. Check All Quadruplets (Brute Force)
Intuition
Iterate with 4 nested loops across arrays of size n: for each a in nums1, b in nums2, c in nums3, d in nums4, check if a + b + c + d == 0. If so, increment count.
When to apply: Use to understand the 4-tuple zero-sum requirement.
Four Nested Loops (O(N^4) Time)
2 of 2 questions left todayEvaluate first combination out of 2^4 = 16 quadruples
Hash map state
Execution stateEvaluate first combination out of 24 = 16 quadruples.
public class Main { public static class Solution { public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) { int count = 0; for (int a : nums1) { for (int b : nums2) { for (int c : nums3) { for (int d : nums4) { if (a + b + c + d == 0) count++; } } } } return count; } } public static void main(String[] args) { Solution sol = new Solution(); int[] nums1 = {1, 2}, nums2 = {-2, -1}, nums3 = {-1, 2}, nums4 = {0, 2}; System.out.println("Tuple count: " + sol.fourSumCount(nums1, nums2, nums3, nums4)); }}Time & Space Complexity
- Time complexity:
O(n^4)— Four nested loops over arrays of size n. - Space complexity:
O(1)— O(1) auxiliary space.
Why Brute Force Doesn't Scale:
At N = 200, N4 exceeds 1.6 billion operations, timing out on modern online judges.
The Meet-in-the-Middle hash map approach performs 40,000 insertions and 40,000 lookups (80,000 operations total), executing in under 30ms.