Problems/Two Pointers/Triplet Sum
Two Pointers
medium

Triplet Sum

Given an array of integers, find all unique triplets that sum to a specified target value. The order of triplets and elements within triplets does not matter.

arraystwo pointerssortingtripletssum

Problem Statement

You are given an array of integers, nums, and a target integer, target. Your task is to find all unique triplets (a, b, c) in nums such that a + b + c = target. The solution set should not contain duplicate triplets. The order of the triplets in the output, and the order of the numbers within each triplet, is not significant.

Example 1
Input: nums = [1, -2, 0, 5, -1, -2], target = 2
Output: [[-2, -1, 5], [-2, 1, 3], [-1, 0, 3]]
The triplets [-2, -1, 5], [-2, 1, 3], and [-1, 0, 3] are the only unique triplets in the input array that sum to the target value of 2.
Example 2
Input: nums = [0, 0, 0, 0], target = 0
Output: [[0, 0, 0]]
The only unique triplet that sums to 0 is [0, 0, 0].
Constraints
  • -3 <= nums.length <= 300
  • --100 <= nums[i] <= 100
  • --300 <= target <= 300

Brute Force Approach

A straightforward approach would be to examine every possible combination of three numbers in the array. This is like trying every possible combination lock setting until you find the right one.

TimeO(n^3)
SpaceO(n)

Ready to practice?

Work through this problem with AI coaching and get real-time feedback

Practice This Problem