Medium Searching

Four Sum

Receives an array of integers and a target value, and returns every unique quadruplet of values from the array that adds up to the target. It first sorts the array, then fixes the first two elements with nested loops (i, j) and searches the remaining range with two pointers moving inward from both ends: if the four-value sum is too small the left pointer advances, if too large the right pointer retreats, and if it matches the quadruplet is recorded before both pointers skip past any duplicate values. Each of the four loop levels (i, j, left, right) also skips over a value equal to its predecessor at the same level, which is what keeps the result free of duplicate quadruplets even when the input has repeated numbers. Returns a new array of four-value arrays in the order they were found; returns an empty array when no quadruplet sums to the target.

Visualization

Input

Algorithm code

Custom input

Saved inputs

References