![]() |
VOOZH | about |
Given an array arr[], the task is to find all possible indices {i, j, k} of triplet {arr[i], arr[j], arr[k]} such that their sum is equal to zero and all indices in a triplet should be distinct (i != j, j != k, k != i). We need to return indices of a triplet in sorted order, i.e., i < j < k.
Examples :
Input: arr[] = [0, -1, 2, -3, 1]
Output: [[0, 1, 4], [2, 3, 4]]
Explanation: Two triplets with sum 0 are:
arr[0] + arr[1] + arr[4] = 0 + (-1) + 1 = 0
arr[2] + arr[3] + arr[4] = 2 + (-3) + 1 = 0Input: arr[] = [1, -2, 1, 0, 5]
Output: [[0, 1, 2]]
Explanation: Only triplet which satisfies the condition is arr[0] + arr[1] + arr[2] = 1 + (-2) + 1 = 0
Input: arr[] = [2, 3, 1, 0, 5]
Output: []
Explanation: There is no triplet with sum 0
Table of Content
The simplest approach is to generate all possible triplets using three nested loops and if the sum of any triplet is equal to zero then add it to the result.
0 1 4 2 3 4
- The idea is to use a hash map to store indices of each element and efficiently find triplets that sum to zero.
- We iterate through all pairs
(j, k), compute the required third element as-(arr[j] + arr[k]), and check if it exists in the map with a valid indexi < j.- If found, we store
{i, j, k}in the result. To ensure unique triplets, the map maintains only indices less than the currentj.- In the worst case, this approach also takes O(n^3) time but in the average case, it is much faster than Naive approach as we are iterating over only those triplets whose sum is equal to target.
0 1 4 2 3 4
Please refer 3Sum - Complete Tutorial for all list of problems on triplets in an array.