Skip to main content

Shrinking Frame Distinct Triplets

medium
ArrayTwo PointersSortingTwo Pointer Pair Sum
Asked atAmazonGoogleMetaMicrosoftBloomberg

Problem Description

Given a sorted array of integers `sortedVals`, find all unique triplets `(a, b, c)` such that `a + b + c = 0`.

The solution set must not contain duplicate triplets. Each triplet should be returned in non-decreasing order, and the list of triplets may be in any order.

**Example 1:**
```
Input: sortedVals = [-4, -2, -1, 0, 1, 2, 3, 5]
Output: [[-4, -1, 5], [-4, 1, 3], [-4, 2, 2], [-2, -1, 3], [-2, 0, 2], [-1, 0, 1]]
```

**Example 2:**
```
Input: sortedVals = [-3, -3, 0, 3, 3]
Output: [[-3, 0, 3]]
Explanation: Duplicate triplets are excluded.
```

Constraints

  • 3 <= sortedVals.length <= 3000
  • -10^5 <= sortedVals[i] <= 10^5
  • sortedVals is sorted in non-decreasing order

Follow-up

Can you solve the four-sum variant (find all unique quadruplets summing to a given target) with O(n³) time?

Hints

Try the problem first. If you get stuck, you can reveal hints one at a time.

Solution

Leaderboard

No entries yet for python.

Be the first — submit an accepted solution.