I was doing 3sum question on leetcode
Question
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]
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
My solution
For this I wrote the following solution but this is giving me Time Limit Exceeded
error.
var threeSum = function(nums) {
// Creating triplet memory so there are any duplicates
const triplet_memory = {}
// num occurrence will have all the numbers in the input array and number of time they occured
const num_occurence = {}
nums.forEach((element) => {
if (!num_occurence.hasOwnProperty(element)) {
num_occurence[element] = 1
} else {
num_occurence[element] += 1
}
})
// iterating over input array
nums.forEach((elParent, indexParent) => {
// Nested loop so that I try all possible combination
nums.forEach((elChild, indexChild) => {
if (indexParent !== indexChild) {
// decreasing the value of current element from our object
// created copied_num_mem so that we don't change main object memeory
const copied_num_mem = {...num_occurence}
// We are decreasing the elParent and elChild value because for currentSum we are utilizing those value
// For example if elParent is 1 and elChild = 2, we would be using those value in our currentSum hence we are decreasing their count by 1
copied_num_mem[elParent] = copied_num_mem[elParent] - 1
copied_num_mem[elChild] = copied_num_mem[elChild] - 1
// multiplying by -1 because suppose we have elParent as -1 and elChild as -1, their sum would give us -2 and we would need the reciprocal of -2 i.e 2 to make it positive
const currentSum = (parseInt(elParent) + parseInt(elChild))*-1
// Checking if 2 exist in our copied_num_mem and if yes, it's value is greater than 0
if (copied_num_mem.hasOwnProperty(currentSum.toString()) && copied_num_mem[currentSum.toString()] > 0) {
// 2, -1, -1 and -1, 2, -1 all are triplets, we are sorting it so that the order of triplet is always the same and we are going to then store that triplet in our triplet_memory
const tripletInt = [currentSum, parseInt(elParent), parseInt(elChild)].sort((a, b) => a -b)
const tripletStringified = tripletInt.join('/')
triplet_memory[tripletStringified] = true
}
}
})
})
const finalErr = []
Object.keys(triplet_memory).forEach(el => {
const elements = el.split('/').map((element) => {
return parseInt(element)
})
finalErr.push(elements)
})
return finalErr
};
console.dir(threeSum([0,0,0]))
console.dir(threeSum([-1,0,1,2,-1,-4]))
Can someone help me in optimizing the algorithm? I have added comments so it should be easy to understand the code.