Skip to content

visual walkthrough

4Sum

MediumSort + Two PointersReported at: AmazonMetaApple+5

Generalises the k-sum reduction and overflow awareness.

Solve on LeetCode

The idea

It is 3Sum with one more loop. Sort, fix two numbers, then squeeze the remaining pair with two pointers, skipping repeated values so each quadruplet appears once.

Each extra fixed number multiplies the work by n, but the final pair always costs just one pass.

Complexity

approachtimespace
Four loopsO(n⁴)O(1)
Sort + two pointersO(n³)O(1)

More walkthroughs