AceYourInterviews
Checking sign-in…

15. 3Sum

AdvancedSorted anchor plus duplicate-aware two pointers

Choose values from three different positions so their sum is zero. Return all distinct triples of values, with each triple written in nondecreasing order.

Different choices of positions can describe the same value triple; that triple must appear only once. Repeated values within a triple still require enough input occurrences.

Example 1

Input

[-1,0,1,2,-1,-4]

Output

[[-1,-1,2],[-1,0,1]]

Explanation: The two -1 occurrences can occupy distinct indices; repeated discovery of the same values is suppressed.

Example 2

Input

[0,0,0,0]

Output

[[0,0,0]]

Explanation: Four index triples represent one value triple.

Constraints

  • 0 <= nums.length <= 3000
  • -231 <= nums[i] <= 231 - 1
  • Return each distinct nondecreasing zero-sum triple once. Outer order is unrestricted.
Hints
Hint 1

Fix one value and solve a two-sum task on the remaining suffix.

Hint 2

How can sorted order prove each pointer move safe?

Hint 3

Skip repeated anchors; after a hit skip both equal partner runs.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Anchor and partner duplicate suppression

[-1,0,1,2,-1,-4]
[[-1,-1,2],[-1,0,1]]