class Solution: def findTriplets(self, arr): mp = dict() n = len(arr) for i in range(n - 1): for j in range(i + 1, n): s = arr[i] + arr[j] if s not in mp: mp[s] = [] mp[s].append([i, j]) ans_set = set() for i in range(n): diff = 0 - arr[i] if diff in mp: tmp = mp[diff] for element in tmp: if element[0] != i and element[1] != i: tmp_arr = [i, element[0], element[1]] tmp_arr.sort() ans_set.add(tuple(tmp_arr)) return [list(triplet) for triplet in ans_set]
Nice explanation brother ❤
Table of Contents
0:00 Problem Statement
0:49 Solution
7:13 Pseudo Code
10:39 Code - Python
11:35 Code - C++
class Solution {
public:
void insert_triplet(set &ans, int i, int j, int k) {
vector tmp = {i, j, k};
sort(tmp.begin(), tmp.end());
//cout
class Solution:
def findTriplets(self, arr):
mp = dict()
n = len(arr)
for i in range(n - 1):
for j in range(i + 1, n):
s = arr[i] + arr[j]
if s not in mp:
mp[s] = []
mp[s].append([i, j])
ans_set = set()
for i in range(n):
diff = 0 - arr[i]
if diff in mp:
tmp = mp[diff]
for element in tmp:
if element[0] != i and element[1] != i:
tmp_arr = [i, element[0], element[1]]
tmp_arr.sort()
ans_set.add(tuple(tmp_arr))
return [list(triplet) for triplet in ans_set]