# Four sum problem to find tuplets - space complexity?

3433 views
6

I am working on below interview question:

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:

Input:

A = [ 1, 2]

B = [-2,-1]

C = [-1, 2]

D = [ 0, 2]

Output: 2

Below is the code and I am not able to understand why the space complexity is O(n^2)? We use only one Map so it should be O(n) space complexity?

``````public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
Map<Integer, Integer> map = new HashMap<>();

for(int i=0; i<C.length; i++) {
for(int j=0; j<D.length; j++) {
int sum = C[i] + D[j];
map.put(sum, map.getOrDefault(sum, 0) + 1);
}
}

int res=0;
for(int i=0; i<A.length; i++) {
for(int j=0; j<B.length; j++) {
res += map.getOrDefault(-1 * (A[i]+B[j]), 0);
}
}

return res;
}
``````

5

it depends on the length of input arrays A,B,C,D

if we assume each array with length `N` that means we have ,

O(NxN) for the first nested loop O(NxN) for the second nested loop

hence we have O(NxN) + O(NxN) = O(2xN^2)

``````= O(N^2)
``````

posted this
8

Let's say `C.length = D.length = N`. You have a loop inside loop. It means, in the first part of the algorithm you call `map.put` function `N*N` times. It gives you already `O(N^2)`. As you use the `HashMap` you can assume that `get` and `put` operations "cost" constant time.

The second part more or less the same. It gives you `O(N^2 + N^2) = O(N^2)`.

posted this