#18

4Sum

Medium Sort + two pointers

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Return all unique quadruplets that add up to target.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: unique quadruplets that hit a target.

Why this works: 3Sum with one more fixed number. Sorting and skipping duplicates keep results unique; use long for the sum.

Example: [1, 0, -1, 0, -2, 2], target 0 → sorted [-2, -1, 0, 0, 1, 2]

fix -2, -1: find (1, 2)fix -2, 0: find (0, 2)fix -1, 0: find (0, 1)

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Adding four ints in int — values up to 10^9 overflow. Cast to long.