medium Triplet Sum to Zero
Problem Statement
Given an array of unsorted numbers, find all unique triplets in it that add up to zero.
Examples
Example 1
- Input: [-3, 0, 1, 2, -1, 1, -2]
- Output: [[-3, 1, 2], [-2, 0, 2], [-2, 1, 1], [-1, 0, 1]]
- Explanation: There are four unique triplets whose sum is equal to zero.
Example 2
- Input: [-5, 2, -1, -2, 3]
- Output: [[-5, 2, 3], [-2, -1, 3]]
- Explanation: There are two unique triplets whose sum is equal to zero.
Constraints:
3 <= arr.length <= 3000- -105 <= arr[i] <= 105
Try it yourself
Try solving this question here:
✅ Solution Triplet Sum to Zero
Problem Statement
Given an array of unsorted numbers, find all unique triplets in it that add up to zero.
Examples
Example 1
- Input: [-3, 0, 1, 2, -1, 1, -2]
- Output: [[-3, 1, 2], [-2, 0, 2], [-2, 1, 1], [-1, 0, 1]]
- Explanation: There are four unique triplets whose sum is equal to zero.
Example 2
- Input: [-5, 2, -1, -2, 3]
- Output: [[-5, 2, 3], [-2, -1, 3]]
- Explanation: There are two unique triplets whose sum is equal to zero.
Constraints:
3 <= arr.length <= 3000- -105 <= arr[i] <= 105
Solution
This problem follows the Two Pointers pattern and shares similarities with Pair with Target Sum. A couple of differences are that the input array is not sorted and instead of a pair we need to find triplets with a target sum of zero.
To follow a similar approach, first, we will sort the array and then iterate through it taking one number at a time. Let’s say during our iteration we are at number ‘X’, so we need to find ‘Y’ and ‘Z’ such that
Another difference from Pair with Target Sum is that we need to find all the unique triplets. To handle this, we have to skip any duplicate number. Since we will be sorting the array, so all the duplicate numbers will be next to each other and are easier to skip.
Step-by-Step Algorithm
-
Sort the Array:
- Sort the input array in non-decreasing order. This helps in easily skipping duplicate elements and applying the two-pointer technique.
-
Iterate through the Array:
- Use a for loop to iterate through the array, stopping at the third-to-last element.
- For each element, check if it's the same as the previous one to avoid duplicates.
- If it's the same, skip to the next iteration.
-
Fix the Current Element and Find Pairs:
- Fix the current element and use two pointers to find pairs whose sum is the negative of the fixed element (
targetSum = -arr[i]). - The left pointer starts from the next element (
i + 1) and the right pointer starts from the end of the array.
- Fix the current element and use two pointers to find pairs whose sum is the negative of the fixed element (
-
Find Pairs with Two Pointers:
- Calculate the sum of the left pointer and the right pointer (
currentSum = arr[left] + arr[right]). - If the
currentSumequalstargetSum, add the triplet to the list ([-targetSum, arr[left], arr[right]]) and move both pointers to the next unique elements. - If
currentSumis less thantargetSum, move the left pointer to the right to increase the sum. - If
currentSumis greater thantargetSum, move the right pointer to the left to decrease the sum.
- Calculate the sum of the left pointer and the right pointer (
-
Skip Duplicates:
- Ensure that the left and right pointers skip duplicate elements to avoid counting the same triplet multiple times.
-
Return the Result:
- After processing all elements, return the list of unique triplets.
Algorithm Walkthrough
Let's visualize example 2 via diagram below.
-
Sort the Array:
- Input:
[-5, 2, -1, -2, 3] - Sorted:
[-5, -2, -1, 2, 3]
- Input:
-
Fix
-5(index 0),leftpointer at-2(index 1), andrightpointer at3(index 4):- Target Sum:
-(-5) = 5 - Sum =
-2 + 3 = 1(less thantargetSum), moveleftto-1(index 2) - Sum =
-1 + 3 = 2(less thantargetSum), moveleftto2(index 3) - Sum =
2 + 3 = 5, found triplet[-5, 2, 3] - Move
leftto 4 andrightto 3 (end of this iteration)
- Target Sum:
-
Fix
-2(index 1),leftpointer at-1(index 2), andrightpointer at3(index 4):- Target Sum:
-(-2) = 2 - Sum =
-1 + 3 = 2, found triplet[-2, -1, 3] - Move
leftto2andrightto 3
- Target Sum:
-
Fix
-1(index 2),leftpointer at2(index 3), andrightpointer at3(index 4):- Target Sum:
-(-1) = 1 - Sum =
2 + 3 = 5(greater thantargetSum), moverightto2(end of this iteration)
- Target Sum:
-
End of loop since all elements are processed.
Output: [[ -5, 2, 3], [ -2, -1, 3]]
Code
Here is what our algorithm will look like:
import java.util.*;
class Solution {
public static List<List<Integer>> searchTriplets(int[] arr) {
Arrays.sort(arr);
List<List<Integer>> triplets = new ArrayList<>();
for (int i = 0; i < arr.length - 2; i++) {
if (
i > 0 && arr[i] == arr[i - 1]
) continue; // skip same element to avoid duplicate triplets
searchPair(arr, -arr[i], i + 1, triplets);
}
return triplets;
}
private static void searchPair(
int[] arr,
int targetSum,
int left,
List<List<Integer>> triplets
) {
int right = arr.length - 1;
while (left < right) {
int currentSum = arr[left] + arr[right];
if (currentSum == targetSum) { // found the triplet
triplets.add(Arrays.asList(-targetSum, arr[left], arr[right]));
left++;
right--;
while (left < right && arr[left] == arr[left - 1]) left++; // skip same element to avoid duplicate triplets
while (left < right && arr[right] == arr[right + 1]) right--; // skip same element to avoid duplicate triplets
} else if (targetSum > currentSum) left++; // we need a pair with a bigger sum
else right--; // we need a pair with a smaller sum
}
}
public static void main(String[] args) {
System.out.println(
Solution.searchTriplets(new int[] { -3, 0, 1, 2, -1, 1, -2 })
);
System.out.println(Solution.searchTriplets(new int[] { -5, 2, -1, -2, 3 }));
}
}
Complexity Analysis:
Time Complexity
-
Sorting the array: The first step in the algorithm is to sort the input array, which takes
, where Nis the number of elements in the input array. -
Outer loop: The main loop runs for each element in the array, excluding the last two, as those will be processed during the pair search. The loop runs approximately
times, which is . -
Inner loop (pair search): For each element processed by the outer loop, the algorithm uses the two-pointer technique to search for pairs that sum to the target value. The two-pointer search for each element takes
time since the pointers traverse the entire array in a linear fashion. -
Overall time complexity: The total time complexity is the sum of the time spent sorting the array and the time spent in the two-pointer search for each element. This gives us a total time complexity of
. Since dominates for large values of N, the overall time complexity is.
Space Complexity
-
Sorting the array: Sorting the array requires additional space, and this adds
space complexity. -
Triplets storage: The space used to store the resulting triplets is
, where Kis the number of triplets found. In the worst case, this could be proportional to, especially if there are many valid triplets. -
Additional variables: The algorithm uses constant extra space for variables like
left,right, andcurrentSum, so this addsto the space complexity.
Overall space complexity:
🤖 Don't fully get this? Learn it with Claude
Stuck on Triplet Sum to Zero? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Triplet Sum to Zero** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Triplet Sum to Zero** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Triplet Sum to Zero**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Triplet Sum to Zero**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.