Problem:

Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
The solution set must not contain duplicate triplets.

Example:
Given array = {-1 0 1 2 -1 -4},
Solution set is:
    (-1, 0, 1)

    (-1, -1, 2)

JavaScript Code

function threeSum(num) {
        //sort array
        num.sort();
 
        var result = [];
        var each = [];
        for(var i=0; i<num.length; i++){
            if(num[i] > 0) break;
 
            for(var j=i+1; j<num.length; j++){
                if(num[i] + num[j] > 0 && num[j] > 0) break;
 
                for(var k=j+1; k<num.length; k++){
                  if(num[i] + num[j] + num[k] == 0) {
 
                      each.push(num[i]);
                      each.push(num[j]);
                      each.push(num[k]);
                      result.push(each);
                      each = [];
                  }
                }
            }
        }
 
       return result;
}

console.log(threeSum([-1,0,1,2,-1,-4]));

2 comments:

  1. js code giving duplicate result as [-1, 0, 1] ???

    ReplyDelete
  2. 4arm-PEG5K-COOH - Alfa Chemistry is an expert in surface modification. We develop and produce surface chemistry technologies to modify various surfaces, such as metals, glasses, and polymers. Our solutions include hydrophobic treatment, oleophobic treatment, waterproof, hydrophilic treatment, anti-fingerprint, and adhesion promotion. These treatments are thin, easy to apply, safe and non-toxic, and provide green options.

    ReplyDelete

Blogroll

Popular Posts