Javascript Time Limit Exceeded

• Hi all,

I tried three solutions for the duplicates problem, but they all time out. I can imagine withe the for loops that would be the case, but I was hoping the maps method would be quick enough (solution1). Has anyone suggestions for a faster solution?

``````
// solution 1
function matcher(num, index, array) {

if (array.indexOf(num)>-1 && array.indexOf(num) !== index){
result.push(num);
return;
} else{
return;
}
}

var findDuplicates = function(nums) {
result = [];
nums.map(matcher);
return result;
};
``````
``````// solution 2
var findDuplicates = function(nums) {
var result = [];
for (var i=0; i<nums.length; i++){
for (var j=0; j<nums.length; j++){
if (i !== j && nums[i] === nums[j]){
result.push(nums[j]);
nums.splice(j,1);
}
}
}
return result;
};
``````
``````// solution 3
var findDuplicates = function(nums) {
var result = [];
var l = nums.length;
var spliced;
for (i=0; i<l; i++){
spliced = nums.splice(0,1);
if (nums.indexOf(spliced[0]) > -1){
result.push(spliced[0]);
}
}
return result;
};
``````

• Ok, I got a working solution. I was not familiar with the hashMap method, but it makes it quite simple:

``````var findDuplicates = function(nums) {
let hashMap = {};
let result = [];
let i;
for (i = 0; i < nums.length; i++){
let num = nums[i];
if (num in hashMap){
result.push(num);
}
hashMap[num] = i;
}
return result;
};
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.