Python coding

Zero-sum picks from four lists

Given four lists of integers a, b, c and d, count the ways to choose one position in each list, i, j, k and l, so that a[i] + b[j] + c[k] + d[l] == 0. Choices are told apart by position: equal values at different positions are different choices. The lists may have different lengths; if one is empty, the answer is 0.

For lists of length n, aim for O(n²).

Besides the tests, one large input (four lists of 150 numbers) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • count_zero_picks([1,-1], [2,0], [-2,1], [0,-1]) → 2
  • count_zero_picks([0], [0], [0], [0]) → 1
  • count_zero_picks([1,1], [-1], [0,0], [0]) → 4
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Four nested loops are O(n⁴), and looking up the last list in a map still leaves O(n³). Split the four lists into two pairs instead.

Hint 2

Count every sum x + y (x from a, y from b) in a Counter. Then, for each sum z + w from c and d, add how many times -(z + w) appeared.

Solution and why it works
pythonO(n²) for four lists of length n · O(n²)
from collections import Counter

def count_zero_picks(a: list[int], b: list[int], c: list[int], d: list[int]) -> int:
    pair_sums = Counter(x + y for x in a for y in b)       # how many (i, j) give each sum
    return sum(pair_sums[-(x + y)] for x in c for y in d)

The total is zero exactly when a[i] + b[j] == -(c[k] + d[l]). Count the n² sums of the first two lists in a map; each of the n² sums of the other two then finds all its partners in one O(1) lookup: O(n²) instead of O(n⁴). Store counts, not a set: two different (i, j) with the same sum are two different choices. This meet in the middle spends O(n²) memory to save the time.

Related lab: Loops in motion