Skip to content
Work Free practice Coding course Blog Method Results Why me About Enquire Book a call

Coding · Two pointers

All distinct triplets summing to zero

Medium · Target 20 minutes · Two pointers · Type asked atOptiverCitadelBloomberg

Given an integer array nums, return every triplet [a, b, c] of values from distinct positions such that a + b + c = 0. Each triplet must be sorted in non-decreasing order, no two triplets may be equal, and the list of triplets must itself be in non-decreasing order.

Examples

InputOutputWhy
nums = [-1, 0, 1, 2, -1, -4][[-1, -1, 2], [-1, 0, 1]]The value −1 appears twice, so it may be used twice — but the triplet [-1, 0, 1] may only be reported once.
nums = [1, 2, 3][]Nothing sums to zero.
nums = [0, 0, 0, 0][[0, 0, 0]]One triplet, not four.

Constraints

  • 3 ≤ n ≤ 3000
  • −10⁵ ≤ nums[i] ≤ 10⁵
  • Positions are distinct; values need not be

Hints

Hint 1

The brute force is three nested loops, O(n³). Before optimising, ask what sorting would buy you.

Hint 2

Fix the first value. What is left is: find two values in the remaining suffix that sum to a known target — the previous problem.

Hint 3

Duplicates are the whole difficulty. Once a value has been used as the fixed element, skip past every copy of it. Do the same for both pointers after recording a hit.

Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.