Find All Triplets with Zero Sum
Given an array Arr
consisting of N
integers, find all distinct triplets in the array that sum up to zero.
Explanation:
An array is said to have a triplet {Arr[i], Arr[j], Arr[k]} with a 0 sum if there exist three indices i
, j
, and k
such that i != j
, j != k
, i != k
, and Arr[i] + Arr[j] + Arr[k] = 0
.
Note:
- You can return the list of values in any order. For example, if a valid triplet is {1, 2, -3}, then {2, -3, 1}, {-3, 2, 1}, etc., is also a valid triplet. Also, the ordering of different triplets can be random; if there are more than one valid triplets, you can return them in any order.
- The elements in the array need not be distinct.
- If no such triplet is present in the array, return an empty list, and the output printed for such a test case will be "-1".
Input:
The first line of the input contains an integer T
, denoting the number of test cases.
The first line of each test case contains the integer N
, denoting the size of the array.
The second line of each test case contains N
space-separated integers denoting the array elements.
Output:
For each test case, every line of output contains three spaced integers that correspond to the elements which add to zero. Refer to sample input 2 for more clarification.
Note:
You do not need to print anything; it has already been taken care of. Just implement the given function.
Constraints:
- 1 <= T <= 50
- 1 <= N <= 10^3
- -10^5 <= Arr[i] <= 10^5
- Time Limit: 1 sec
AnswerBot
2d
Find all distinct triplets in an array that sum up to zero.
Use a nested loop to iterate through all possible combinations of triplets.
Sort the array to easily identify duplicates and skip unnecessary ...read more
Help your peers!
Add answer anonymously...
Top Microsoft Corporation Software Developer interview questions & answers
Popular interview questions of Software Developer
Top HR questions asked in Microsoft Corporation Software Developer
>
Microsoft Corporation Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app