Given an integer array arr
of size n
, find all magic triplets in it.
Magic triplet is a group of three numbers whose sum is zero.
Note that magic triplets may or may not be made of consecutive numbers in arr
.
{
"arr": [10, 3, -4, 1, -6, 9]
}
Output:
["10,-4,-6", "3,-4,1"]
"1,2,-3"
(no whitespace, one comma between numbers).["1,2,-3", "1,-1,0"]
is a correct answer, then ["0,1,-1", "1,-3,2"]
is also a correct answer."1,2,-3"
is a part of an answer, then "1,-3,2"
, "-3,2,1"
or any permutation of the same numbers may not appear in the same answer (though any one of them may appear instead of "1,2,-3"
).Constraints:
n
<= 2000arr
<= 1000arr
may contain duplicate numbersarr
is not necessarily sortedWe have provided two solutions.
A simple solution is to use three nested loops and check for each possible combination if their sum is zero. To avoid duplicate answers, we need to hash the triplet and store it in a set. An easy way to hash a triplet is by converting it to a string.
Extra space needed will be the number of unique triplets that contribute to the answer.
O(n3).
O(1).
O(n2).
/*
* Asymptotic complexity in terms of size of \`arr\` \`n\`:
* Time: O(n^3).
* Auxiliary space: O(1).
* Total space: O(n^2).
*/
static ArrayList<String> find_zero_sum(ArrayList<Integer> arr) {
Set<String> answer = new HashSet<>();
// Sorting is only necessary for avoiding duplicates in the answer.
Collections.sort(arr);
int n = arr.size();
for (int index_1 = 0; index_1 < n; index_1++) {
for (int index_2 = index_1 + 1; index_2 < n; index_2++) {
for (int index_3 = index_2 + 1; index_3 < n; index_3++) {
int sum = arr.get(index_1) + arr.get(index_2) + arr.get(index_3);
if (sum == 0) {
answer.add(arr.get(index_1) + "," + arr.get(index_2) + "," + arr.get(index_3));
}
}
}
}
return new ArrayList<>(answer);
}
This solution uses the Two Pointers Technique. We maintain left and right pointers to elements of a sorted array. If their sum is greater than intended we decrease the right pointer, otherwise we increase the left pointer. This method works in linear time, and to solve this particular problem we use this algorithm n
times, once for each element in arr
.
First, we will sort arr
, that will contribute O(n * log(n)) to the time complexity. Then, for every element or arr
, we will apply the two pointer technique to find any magic triplets that include that element. We will then add unique triplets to the answer.
O(n2 + n * log(n)).
O(1).
O(n2).
/*
Asymptotic complexity in terms of size of the input array \`n\`:
* Time: O(n^2 + n * log(n)).
* Auxiliary space: O(1).
* Total space: O(n^2).
*/
static ArrayList<String> find_zero_sum(ArrayList<Integer> arr) {
Set<String> answer = new HashSet<>();
Collections.sort(arr); // A prerequisite for the two pointer technique to work.
int n = arr.size();
for (int index = 0; index < n; index++) {
int currentElement = arr.get(index);
// We will look for two elements that sum up to this:
int neededSum = -currentElement;
int left = index + 1, right = n - 1;
while (left < right) {
int sum = arr.get(left) + arr.get(right);
if (sum == neededSum) {
answer.add(currentElement + "," + arr.get(left) + "," + arr.get(right));
left++; // "right--" would also work fine here.
// Note that the three numbers in our magic triplet strings
// will always be sorted in the increasing order because
// we sorted the array and because index > left > right.
// That and using a set to store the strings is enough for
// avoiding duplicates in the answer.
} else if (sum > neededSum) {
right--;
} else {
left++;
}
}
}
return new ArrayList<>(answer);
}
We hope that these solutions to the 4 sum problem have helped you level up your coding skills. You can expect problems like these at top tech companies like Amazon and Google.
If you are preparing for a tech interview at FAANG or any other Tier-1 tech company, register for Interview Kickstart’s FREE webinar to understand the best way to prepare.
Interview Kickstart offers interview preparation courses taught by FAANG+ tech leads and seasoned hiring managers. Our programs include a comprehensive curriculum, unmatched teaching methods, and career coaching to help you nail your next tech interview.
We offer 18 interview preparation courses, each tailored to a specific engineering domain or role, including the most in-demand and highest-paying domains and roles, such as:
To learn more, register for the FREE webinar.
Given an integer array arr
of size n
, find all magic triplets in it.
Magic triplet is a group of three numbers whose sum is zero.
Note that magic triplets may or may not be made of consecutive numbers in arr
.
{
"arr": [10, 3, -4, 1, -6, 9]
}
Output:
["10,-4,-6", "3,-4,1"]
"1,2,-3"
(no whitespace, one comma between numbers).["1,2,-3", "1,-1,0"]
is a correct answer, then ["0,1,-1", "1,-3,2"]
is also a correct answer."1,2,-3"
is a part of an answer, then "1,-3,2"
, "-3,2,1"
or any permutation of the same numbers may not appear in the same answer (though any one of them may appear instead of "1,2,-3"
).Constraints:
n
<= 2000arr
<= 1000arr
may contain duplicate numbersarr
is not necessarily sortedWe have provided two solutions.
A simple solution is to use three nested loops and check for each possible combination if their sum is zero. To avoid duplicate answers, we need to hash the triplet and store it in a set. An easy way to hash a triplet is by converting it to a string.
Extra space needed will be the number of unique triplets that contribute to the answer.
O(n3).
O(1).
O(n2).
/*
* Asymptotic complexity in terms of size of \`arr\` \`n\`:
* Time: O(n^3).
* Auxiliary space: O(1).
* Total space: O(n^2).
*/
static ArrayList<String> find_zero_sum(ArrayList<Integer> arr) {
Set<String> answer = new HashSet<>();
// Sorting is only necessary for avoiding duplicates in the answer.
Collections.sort(arr);
int n = arr.size();
for (int index_1 = 0; index_1 < n; index_1++) {
for (int index_2 = index_1 + 1; index_2 < n; index_2++) {
for (int index_3 = index_2 + 1; index_3 < n; index_3++) {
int sum = arr.get(index_1) + arr.get(index_2) + arr.get(index_3);
if (sum == 0) {
answer.add(arr.get(index_1) + "," + arr.get(index_2) + "," + arr.get(index_3));
}
}
}
}
return new ArrayList<>(answer);
}
This solution uses the Two Pointers Technique. We maintain left and right pointers to elements of a sorted array. If their sum is greater than intended we decrease the right pointer, otherwise we increase the left pointer. This method works in linear time, and to solve this particular problem we use this algorithm n
times, once for each element in arr
.
First, we will sort arr
, that will contribute O(n * log(n)) to the time complexity. Then, for every element or arr
, we will apply the two pointer technique to find any magic triplets that include that element. We will then add unique triplets to the answer.
O(n2 + n * log(n)).
O(1).
O(n2).
/*
Asymptotic complexity in terms of size of the input array \`n\`:
* Time: O(n^2 + n * log(n)).
* Auxiliary space: O(1).
* Total space: O(n^2).
*/
static ArrayList<String> find_zero_sum(ArrayList<Integer> arr) {
Set<String> answer = new HashSet<>();
Collections.sort(arr); // A prerequisite for the two pointer technique to work.
int n = arr.size();
for (int index = 0; index < n; index++) {
int currentElement = arr.get(index);
// We will look for two elements that sum up to this:
int neededSum = -currentElement;
int left = index + 1, right = n - 1;
while (left < right) {
int sum = arr.get(left) + arr.get(right);
if (sum == neededSum) {
answer.add(currentElement + "," + arr.get(left) + "," + arr.get(right));
left++; // "right--" would also work fine here.
// Note that the three numbers in our magic triplet strings
// will always be sorted in the increasing order because
// we sorted the array and because index > left > right.
// That and using a set to store the strings is enough for
// avoiding duplicates in the answer.
} else if (sum > neededSum) {
right--;
} else {
left++;
}
}
}
return new ArrayList<>(answer);
}
We hope that these solutions to the 4 sum problem have helped you level up your coding skills. You can expect problems like these at top tech companies like Amazon and Google.
If you are preparing for a tech interview at FAANG or any other Tier-1 tech company, register for Interview Kickstart’s FREE webinar to understand the best way to prepare.
Interview Kickstart offers interview preparation courses taught by FAANG+ tech leads and seasoned hiring managers. Our programs include a comprehensive curriculum, unmatched teaching methods, and career coaching to help you nail your next tech interview.
We offer 18 interview preparation courses, each tailored to a specific engineering domain or role, including the most in-demand and highest-paying domains and roles, such as:
To learn more, register for the FREE webinar.
Attend our free webinar to amp up your career and get the salary you deserve.