0454.4 Sum I I

454. 4Sum II #

Problem #

Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.

To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1.

Example 1:


Input:
A = [ 1, 2]
B = [-2,-1]
C = [-1, 2]
D = [ 0, 2]

Output:
2

Explanation:
The two tuples are:
1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0

Problem Summary #

Given 4 arrays, calculate how many tuples i, j, k, l exist such that A[i] + B[j] + C[k] + D[l] = 0.

Solution Approach #

The data size of this problem is not large, 0 ≤ N ≤ 500, but if a brute-force solution with four nested loops is used, it will time out. The idea for this problem is also similar to the idea for Problem 1: first store all combinations of 2 arrays in a map. Then loop through the remaining 2 arrays and find combinations whose sum is 0. This way the time complexity is O(n^2). Of course, you can also store the combinations of the remaining 2 arrays in a map as well, but finally searching for the result in the 2 maps also has a time complexity of O(n^2).

Code #


package leetcode

func fourSumCount(A []int, B []int, C []int, D []int) int {
	m := make(map[int]int, len(A)*len(B))
	for _, a := range A {
		for _, b := range B {
			m[a+b]++
		}
	}
	ret := 0
	for _, c := range C {
		for _, d := range D {
			ret += m[0-c-d]
		}
	}

	return ret
}


Calendar Jun 25, 2026
Edit Edit this page
Total visits:   You are visitor No.
中文