Given an array nums
of n integers, are there elements a, b, c in nums
such that a + b + c= 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4]
Given an array
nums
of n integers, are there elements a, b, c in nums
such that a + b + c= 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4]
Solution in javascript with explanation of the logic in plain english below:
const threeSum = (nums, target) => {
const hash = {};
const ans = [];
for (let i = 0; i < nums.length; i++) {
for (key in hash) {
if(hash[key][target - (nums[i] + +key)] === undefined) {
hash[key][nums[i]] = null;
} else {
hash[key][target - (nums[i] + +key)] = nums[i];
ans.push([+key, target - (nums[i] + +key), nums[i]]);
}
}
if (hash[nums[i]] === undefined) {
hash[nums[i]] = {}
}
}
return ans;
}
Example
console.log(threeSum([-1, 0, 1, 2, -1, -4], 0));
Output
[ [ -1, 0, 1 ], [ 0, 1, -1 ], [ -1, 2, -1 ] ]
Explanation
{
-1: {0:1, 1:null, 2:-1, -1:null, -4:null},
0: {1:-1, 2: null, -1:null, -4:null},
1: {2: null, -1:null, -4: null},
2: {-1:null, -4:null},
-4: {}
}
- iterate through array > if not in object, add to object
- iterate through objects > if not in object of object, add it with value as null | else log
Comments
Post a Comment