Problem
FAANG · LeetCode #454

4Sum II — three-stage drill

1The ProblemMedium

4Sum II

Count tuples (a,b,c,d), one from each array, summing to zero.

count tuples (a, b, c, d) with a + b + c + d = 0A12B-2-1C-12D021 + (−2) + (−1) + 2 = 02 + (−1) + (−1) + 0 = 0return2
Examples
A=[1,2] B=[-2,-1] C=[-1,2] D=[0,2]→ 2

constraintFour arrays of equal length n; count index tuples, not values.

2The PatternTIME O(n) · SPACE O(n)

Arrays & Hashing

Trade space for time: a hash map turns 'have I seen this?' into an O(1) lookup.

remember what you've seen in a hash map → O(1) lookup4021722344scan›value → countseen = {4: 1}
Problems using this pattern
3The SolutionRESULT → 2

Step through it

phase 1 — tally every a + b sumA12B-2-11 + (-2) = -1 → map[-1]++a+b → countsums = {-1: 1← tallied}
build: 1 + (−2) = −1 → map[−1] = 1
Step 1 / 8
Arrow keys to navigate · escape to reset

All problems by pattern

Backtracking

Recursive Descent