InferenceAI

Enter at least two characters to search.

Start free

Zero-Sum Triplets

mediumTwo Pointers25 min25 XP

Return all unique triplets [a, b, c] from nums with a+b+c=0a + b + c = 0.

Each triplet must be sorted (a≤b≤ca \le b \le c) and the list of triplets must be sorted. No triplet may appear twice.

Requirements

  • Aim for O(n2)O(n^2) time by sorting first and using two pointers.

Examples

EXAMPLE WALKTHROUGHtwo triplets

A guided view of the published example, not a trace of your code.

INPUT[[-1,0,1,2,-1,-4]]
TASKzero_sum_triplets()
EXPECTED OUTPUT[[-1,-1,2],[-1,0,1]]

Start with the input values shown in this example.

Example 1 of 3

Input: nums = [-1,0,1,2,-1,-4]

Output: [[-1,-1,2],[-1,0,1]]

Explanation: two triplets

Input: nums = [0,1,1]

Output: []

Explanation: none

Input: nums = [0,0,0,0]

Output: [[0,0,0]]

Explanation: all zeros

Hint 1

Sort the list. Fix the first value, then find pairs in the rest with two pointers.

Hint 2

Skip equal neighbours to avoid duplicate triplets.

Topics

DSATwo PointersPython