![]() |
VOOZH | about |
Given an array arr[] and an integer target, 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 given target 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}, target = -2
Output: {{0, 3, 4}, {1, 2, 3}}
Explanation: Two triplets that add up to -2 are:
arr[0] + arr[3] + arr[4] = 0 + (-3) + (1) = -2
arr[1] + arr[2] + arr[3] = (-1) + 2 + (-3) = -2
Input: arr[] = {1, -2, 1, 0, 5}, target = 1
Output: {}
Explanation: There is no triplet whose sum is equal to 1.
Table of Content
The naive approach is to explore all the triplets using three nested loops and if the sum of any triplet is equal to given target then add it to the result.
0 3 4 1 2 3
The idea is to store sum of all the pairs with their indices in the hash map or dictionary. Then, for each element in the array, we check if the pair which makes triplet's sum zero, exists in the hash map or not. Since there can be multiple valid pairs, we add each one to the hash set (to manage duplicates) while ensuring that all indices in the triplet are distinct.
In the worst case, this approach also has O(n^3) Time Complexity but in the average case, it is much faster than the Naive Approach as we are iterating over only those triplets whose sum is equal to target.
0 3 4 1 2 3