Talentd
FleetCode
Make and follow sheets.Sign in

4Sum II solution and explanation

MediumArrayHash Table5 min read57.9% acceptanceUpdated 9 Apr 2026
Quadruplet Sum II HashMap and Heap | Leetcode 454. 4sum ii SolutionPepcoding · 12:02 · 7K viewsWatch on YouTube
9 more videos on this problem
  1. Quadruplet Sum II HashMap and Heap | Leetcode 454. 4sum ii SolutionPepcoding · 12:02 · 7K views
  2. 4Sum II | Live Coding with Explanation | Leetcode - 454Algorithms Made Easy · 3:46 · 6K views
  3. 4 Sum II | Leetcode 454 | ArraysAyushi Sharma · 21:52 · 5K views
  4. Leetcode 454. 4 Sum || Leetcode Daily Challenge tuples nums1[i] + nums2[j] + nums3[k] + nums4[l] ==0Code with Alisha · 11:25 · 3K views
  5. 4Sum II | Leetcode 454 | Live coding session 🔥🔥🔥 | 3 Approaches | o(n2) | O(n3) | O(n4)Coding Decoded · 7:46 · 1K views
  6. 454. 4Sum II | #18 | Hash Table Playlist #hashtable #leetcode #algorithmsCTO Bhaiya · 16:51 · 1K views
  7. 454. 4Sum II (Leetcode Problem)viralSongs · 5:24 · 1K views
  8. 4Sum II - Leetcode Interview QuestionAryan Mittal · 9:35 · 1K views
  9. Daily Leetcode #674: Feb 03, 2022 - 454. 4Sum IIProgramming Live with Larry · 9:57 · 874 views
  10. Daily Leetcode #261: Dec 17, 2020 - 454. 4Sum IIProgramming Live with Larry · 5:42 · 758 views

The problem

Given four integer arrays nums1, nums2, nums3, and nums4 all of length n, return the number of tuples (i, j, k, l) such that:

  • 0 <= i, j, k, l < n
  • nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0

Example 1:

Input: nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]
Output: 2
Explanation:
The two tuples are:
1. (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0
2. (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0

Example 2:

Input: nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0]
Output: 1

Constraints:

  • n == nums1.length
  • n == nums2.length
  • n == nums3.length
  • n == nums4.length
  • 1 <= n <= 200
  • -228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228

Approach overview

Problem Overview: You are given four integer arrays A, B, C, and D. The goal is to count how many tuples (i, j, k, l) satisfy A[i] + B[j] + C[k] + D[l] = 0. A naive approach checks every possible combination, but the real challenge is reducing the exponential search using a smarter lookup strategy.

Approach 1: Brute Force with Four Nested Loops (O(n4) time, O(1) space)

The most direct method iterates through every element of all four arrays using four nested loops. For each combination (i, j, k, l), compute the sum and increment the result when it equals zero. This approach demonstrates the full search space and confirms correctness, but it quickly becomes impractical as n grows. With arrays of size 200, the algorithm may check billions of combinations. This version mainly serves as a conceptual baseline before optimizing with better data structures.

Approach 2: Hash Map Pair Sums (O(n2) time, O(n2) space)

The optimal solution reduces the four-sum problem into two independent two-sum problems. First iterate through arrays A and B and compute every possible pair sum a + b. Store these sums in a hash map where the key is the sum and the value is the number of times that sum appears. This preprocessing step takes O(n2) time.

Next iterate through arrays C and D. For each pair compute c + d, then check if -(c + d) exists in the hash map. A constant-time hash lookup immediately tells you how many matching pairs from A and B can complete the equation. Add that frequency to the answer. This effectively counts all tuples whose sums cancel out to zero.

The key insight: instead of evaluating four numbers at once, precompute half of the equation and reuse it with fast lookups. The hash table stores pair frequencies, while the arrays are scanned with simple nested loops. This reduces the search space from n⁴ combinations to roughly 2 * n² operations. The idea is common in multi-sum problems and builds directly on patterns from array pair-sum techniques.

Recommended for interviews: Interviewers expect the hash map pair-sum solution. Starting with the brute force approach shows you understand the problem space, but optimizing to O(n²) using a frequency map demonstrates algorithmic insight and familiarity with hash-based counting patterns. This approach balances performance and clarity, and it is the standard solution used in most production implementations.

Approach 1: Using Hash Maps to Store Sums

This approach leverages hash maps to efficiently count and use pair sums. First, we compute all possible sums between arrays nums1 and nums2, storing them in a hash map along with their count. Then, we iterate over pairs of nums3 and nums4, checking how many complements (to form a sum of zero) exist in the hash map.

from collections import Counter

def fourSumCount(nums1, nums2, nums3, nums4):
    sum_map = Counter(a + b for a in nums1 for b in nums2)
    return sum(sum_map[-c - d] for c in nums3 for d in nums4)
import java.util.HashMap;
import java.util.Map;

public class FourSumII {
    public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        Map<Integer, Integer> map = new HashMap<>();
        int count = 0;
        
        for (int a : nums1) {
            for (int b : nums2) {
                map.put(a + b, map.getOrDefault(a + b, 0) + 1);
            }
        }
        
        for (int c : nums3) {
            for (int d : nums4) {
                count += map.getOrDefault(-(c + d), 0);
            }
        }
        
        return count;
    }
}
#include <unordered_map>
#include <vector>
using namespace std;

int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) {
    unordered_map<int, int> sumMap;
    int count = 0;
    
    for (int a : nums1) {
        for (int b : nums2) {
            sumMap[a + b]++;
        }
    }
    
    for (int c : nums3) {
        for (int d : nums4) {
            int complement = -(c + d);
            if (sumMap.count(complement)) {
                count += sumMap[complement];
            }
        }
    }
    
    return count;
}
function fourSumCount(nums1, nums2, nums3, nums4) {
    const sumMap = new Map();
    let count = 0;
    
    for (let a of nums1) {
        for (let b of nums2) {
            const sum = a + b;
            sumMap.set(sum, (sumMap.get(sum) || 0) + 1);
        }
    }
    
    for (let c of nums3) {
        for (let d of nums4) {
            const complement = -(c + d);
            if (sumMap.has(complement)) {
                count += sumMap.get(complement);
            }
        }
    }
    
    return count;
}
#include <stdlib.h>

typedef struct {
    int key;
    int value;
    UT_hash_handle hh;
} HashMapItem;

int fourSumCount(int* nums1, int nums1Size, int* nums2, int nums2Size, int* nums3, int nums3Size, int* nums4, int nums4Size) {
    HashMapItem* hashMap = NULL;
    HashMapItem* item;
    int count = 0;
    
    // Calculating sums of pairs from nums1 and nums2
    for (int i = 0; i < nums1Size; i++) {
        for (int j = 0; j < nums2Size; j++) {
            int sum = nums1[i] + nums2[j];
            HASH_FIND_INT(hashMap, &sum, item);
            if (item == NULL) {
                item = (HashMapItem*)malloc(sizeof(HashMapItem));
                item->key = sum;
                item->value = 1;
                HASH_ADD_INT(hashMap, key, item);
            } else {
                item->value++;
            }
        }
    }
    
    // Calculating sums of pairs from nums3 and nums4
    for (int k = 0; k < nums3Size; k++) {
        for (int l = 0; l < nums4Size; l++) {
            int sum = -(nums3[k] + nums4[l]);
            HASH_FIND_INT(hashMap, &sum, item);
            if (item != NULL) count += item->value;
        }
    }
    
    // Free the hash map
    HASH_CLEAR(hh, hashMap);
    
    return count;
}
using System;
using System.Collections.Generic;

public class Solution {
    public int FourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        Dictionary<int, int> sumMap = new Dictionary<int, int>();
        int count = 0;

        foreach (int a in nums1) {
            foreach (int b in nums2) {
                int sum = a + b;
                if (sumMap.ContainsKey(sum)) {
                    sumMap[sum]++;
                } else {
                    sumMap[sum] = 1;
                }
            }
        }

        foreach (int c in nums3) {
            foreach (int d in nums4) {
                int complement = -(c + d);
                if (sumMap.ContainsKey(complement)) {
                    count += sumMap[complement];
                }
            }
        }

        return count;
    }
}

The Python solution utilizes a Counter from the collections module to hold pair sums from nums1 and nums2. It then calculates the sum of occurrences for complementary sums involving nums3 and nums4, giving the total count of zero-sum tuples.

Complexity

Time Complexity: O(n^2), achieved due to the two dominant nested loops for sum computation.
Space Complexity: O(n^2), to hold pair sums in the Counter.

Try this approach in the editor

Approach 2: Hash Table

We can add the elements a and b in arrays nums1 and nums2 respectively, and store all possible sums in a hash table cnt, where the key is the sum of the two numbers, and the value is the count of the sum.

Then we iterate through the elements c and d in arrays nums3 and nums4, let c+d be the target value, then the answer is the cumulative sum of cnt[-(c+d)].

The time complexity is O(n^2), and the space complexity is O(n^2), where n is the length of the array.

function fourSumCount(nums1: number[], nums2: number[], nums3: number[], nums4: number[]): number {
    const cnt: Record<number, number> = {};
    for (const a of nums1) {
        for (const b of nums2) {
            const x = a + b;
            cnt[x] = (cnt[x] || 0) + 1;
        }
    }
    let ans = 0;
    for (const c of nums3) {
        for (const d of nums4) {
            const x = c + d;
            ans += cnt[-x] || 0;
        }
    }
    return ans;
}
func fourSumCount(nums1 []int, nums2 []int, nums3 []int, nums4 []int) (ans int) {
	cnt := map[int]int{}
	for _, a := range nums1 {
		for _, b := range nums2 {
			cnt[a+b]++
		}
	}
	for _, c := range nums3 {
		for _, d := range nums4 {
			ans += cnt[-(c + d)]
		}
	}
	return
}
use std::collections::HashMap;

impl Solution {
    pub fn four_sum_count(
        nums1: Vec<i32>,
        nums2: Vec<i32>,
        nums3: Vec<i32>,
        nums4: Vec<i32>,
    ) -> i32 {
        let mut cnt = HashMap::new();
        for &a in &nums1 {
            for &b in &nums2 {
                *cnt.entry(a + b).or_insert(0) += 1;
            }
        }
        let mut ans = 0;
        for &c in &nums3 {
            for &d in &nums4 {
                if let Some(&count) = cnt.get(&(0 - (c + d))) {
                    ans += count;
                }
            }
        }
        ans
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Using Hash Maps to Store Sums

Time Complexity: O(n^2), achieved due to the two dominant nested loops for sum computation.
Space Complexity: O(n^2), to hold pair sums in the Counter.

Hash Table–

Complexity analysis

ApproachTimeSpaceWhen to Use
Brute Force Four Nested LoopsO(n^4)O(1)Small input sizes or when explaining the baseline logic before optimization
Hash Map Pair SumsO(n^2)O(n^2)General case and interview solution; efficient counting using hash map lookups

Frequently asked questions

Is 4Sum II easy or hard?

4Sum II is rated Medium difficulty. The brute force idea is straightforward, but recognizing the pair-sum hash map optimization requires familiarity with hash-based counting patterns.

4Sum II Python/Java solution

Python and Java implementations follow the same strategy: compute pair sums of the first two arrays using a dictionary or HashMap, then iterate through the other two arrays and accumulate matches using complement lookups.

How to solve 4Sum II in O(n^2)?

Precompute all pair sums from arrays A and B and store them in a hash map with their frequencies. Then iterate over pairs from C and D and check if the complement -(c + d) exists in the map. Each lookup counts how many valid tuples complete the zero sum.

What is the best approach for 4Sum II?

The hash map pair-sum approach is the most efficient. Compute all sums of A[i] + B[j] and store their frequencies in a hash map. Then iterate through pairs from C and D and look up the complement -(c + d). This reduces the complexity from O(n^4) to O(n^2).

Is 4Sum II asked at Google/Amazon/Meta?

Variants of multi-sum and pair-sum counting problems appear in interviews at companies like Amazon, Google, and Meta. The problem tests hash map usage, frequency counting, and the ability to reduce a higher-dimensional search space.

What data structure is used in 4Sum II?

A hash map (hash table) is the primary data structure. It stores frequencies of pair sums so the algorithm can perform constant-time lookups while scanning the remaining arrays.

What is the time complexity of 4Sum II?

The optimal solution runs in O(n^2) time. It builds a hash map of pair sums from the first two arrays in O(n^2), then scans pair sums from the remaining arrays with constant-time hash lookups.

Comments

Now write it yourselfClose this page and solve 4Sum II in the editor, without looking.
Practise 4Sum II