LeetCode Solutions

454. 4Sum II

Time: $O(n^2)$

Space: $O(n^2)$

			

class Solution {
 public:
  int fourSumCount(vector<int>& A, vector<int>& B,
                   vector<int>& C, vector<int>& D) {
    int ans = 0;
    unordered_map<int, int> count;

    for (const int a : A)
      for (const int b : B)
        ++count[a + b];

    for (const int c : C)
      for (const int d : D)
        if (count.count(-c - d))
          ans += count[-c - d];

    return ans;
  }
};
			

class Solution {
  public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
    int ans = 0;
    Map<Integer, Integer> count = new HashMap<>();

    for (final int a : A)
      for (final int b : B)
        count.put(a + b, count.getOrDefault(a + b, 0) + 1);

    for (final int c : C)
      for (final int d : D)
        if (count.containsKey(-c - d))
          ans += count.get(-c - d);

    return ans;
  }
}
			

class Solution:
  def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
    count = Counter(a + b for a in A for b in B)

    return sum(count[-c - d] for c in C for d in D)