Sorting Problem

3 Sum

Problem

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.

Example

{
"arr": [10, 3, -4, 1, -6, 9]
}

Output:

["10,-4,-6", "3,-4,1"]

Solution

function find_zero_sum(arr) {
    // Write your code here.
    var len = arr.length;
    var ans = [];
    arr.sort((a,b) => (a-b));
    
    for(var i=0; i < len-1; i++) {
        
        var s = new Set();
        
        for(var j = i+1; j < len; j++) {
            
            var x = -(arr[i] + arr[j]);
            
            if(s.has(x)) {
                var k = x + "," + arr[i] + "," + arr[j];
                ans.push(k);
            } else {
                s.add(arr[j]);
            }
        }
    }
    
    return ans;
}

Time and Space Complexity

Time Complexity : O(n3)
Space Complexity:  O(1)

Leave a comment