4Sum II

medium array hash map

Problem

Given four integer arrays A, B, C, D of equal length, return the number of tuples (i, j, k, l) such that A[i] + B[j] + C[k] + D[l] == 0.

InputA=[1,2], B=[-2,-1], C=[-1,2], D=[0,2]
Output2
(0,0,0,1) → 1 + −2 + −1 + 2 = 0; (1,1,0,0) → 2 + −1 + −1 + 0 = 0.

from collections import Counter
def four_sum_count(A, B, C, D):
    ab = Counter()
    for a in A:
        for b in B:
            ab[a + b] += 1
    count = 0
    for c in C:
        for d in D:
            count += ab.get(-(c + d), 0)
    return count
function fourSumCount(A, B, C, D) {
  const ab = new Map();
  for (const a of A) for (const b of B) ab.set(a + b, (ab.get(a + b) || 0) + 1);
  let count = 0;
  for (const c of C) for (const d of D) count += ab.get(-(c + d)) || 0;
  return count;
}
class Solution {
    public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
        Map<Integer, Integer> ab = new HashMap<>();
        for (int a : A) for (int b : B) ab.merge(a + b, 1, Integer::sum);
        int count = 0;
        for (int c : C) for (int d : D) count += ab.getOrDefault(-(c + d), 0);
        return count;
    }
}
int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
    unordered_map<int, int> ab;
    for (int a : A) for (int b : B) ab[a + b]++;
    int count = 0;
    for (int c : C) for (int d : D) {
        auto it = ab.find(-(c + d));
        if (it != ab.end()) count += it->second;
    }
    return count;
}
Time: O(n²) Space: O(n²)