Ctrl K

Four Lists, Zero Total

Medium
You are given four integer lists first, second, third and fourth, all of the same length n. Picking one element from each list gives an index quadruple (i, j, k, l). Count the quadruples for which first[i] + second[j] + third[k] + fourth[l] == 0. Quadruples are told apart by their indices, not their values: if a list has repeats, each position counts separately. Brute force takes O(n⁴); aim for O(n²).
Example 1
first=[3, -1], second=[0, 2], third=[-2, 1], fourth=[-1, -3] → 2

Exactly two index quadruples work: (0, 0, 0, 0) gives 3 + 0 + (-2) + (-1) = 0, and (0, 1, 0, 1) gives 3 + 2 + (-2) + (-3) = 0. The other 14 combinations do not add up to zero.

Example 2
first=[1, 1], second=[-1, -1], third=[0, 0], fourth=[0, 0] → 16

Every choice gives 1 - 1 + 0 + 0 = 0, so all 2 · 2 · 2 · 2 = 16 quadruples count. Equal values at different positions are different choices.

Example 3
first=[4], second=[-1], third=[2], fourth=[6] → 0

The only quadruple sums to 4 - 1 + 2 + 6 = 11, not 0.

Constraints
  • 1 ≤ n ≤ 200
  • All four lists have length n
  • -2²⁸ ≤ every element ≤ 2²⁸
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSudoku Board Without Clashes MediumAnagram Buckets MediumZero Out the Crosses MediumTree From Pre-Order and In-Order Walks MediumTree From In-Order and Post-Order Walks Medium
loading Python…
Input
first=[3, -1], second=[0, 2], third=[-2, 1], fourth=[-1, -3]
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 99 tests on the server, hidden ones included.