
Problem
Solution
Submissions
Find Unique Triplets with Target Sum
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 8
Write a C# function to find all unique triplets in an array that sum to a specified target value. A triplet is a set of three integers. The solution should avoid duplicate triplets in the output.
Example 1
- Input: nums = [-1, 0, 1, 2, -1, -4], target = 0
- Output: [[-1, -1, 2], [-1, 0, 1]]
- Explanation:
- Step 1: Sort the input array (for efficient processing): [-4, -1, -1, 0, 1, 2].
- Step 2: Iterate through the array, fixing the first element of potential triplets.
- Step 3: For each fixed element, use two pointers technique to find pairs that complete the triplet.
- Step 4: When a triplet is found (nums[0] + nums[4] + nums[2] = -1 + (-1) + 2 = 0), add it to results.
- Step 5: Skip duplicate elements to avoid duplicate triplets.
- Step 6: Repeat until all unique triplets are found ([-1, -1, 2], [-1, 0, 1]).
Example 2
- Input: nums = [1, 2, 3, 4, 5], target = 12
- Output: [[3, 4, 5]]
- Explanation:
- Step 1: Sort the input array (already sorted): [1, 2, 3, 4, 5].
- Step 2: Iterate through the array, fixing the first element of potential triplets.
- Step 3: For each fixed element, use two pointers technique to find pairs that complete the triplet.
- Step 4: When a triplet is found (nums[2] + nums[3] + nums[4] = 3 + 4 + 5 = 12), add it to results.
- Step 5: No other triplets sum to 12, so return [[3, 4, 5]].
Constraints
- 3 ≤ nums.length ≤ 3000
- -10^5 ≤ nums[i] ≤ 10^5
- -10^5 ≤ target ≤ 10^5
- Time Complexity: O(n²) where n is the length of the array
- Space Complexity: O(n) for storing the results
Editorial
My Submissions
All Solutions
| Lang | Status | Date | Code |
|---|---|---|---|
| You do not have any submissions for this problem. | |||
| User | Lang | Status | Date | Code |
|---|---|---|---|---|
| No submissions found. | ||||
Solution Hints
- Sort the array to avoid duplicate triplets
- Use a two-pointer approach for each element
- Fix one element and find the other two using the two-pointer technique
- Skip duplicate elements to avoid duplicate triplets
- Use a set or list to store unique triplets