Search code examples
javascriptruntime

how to improve JavaScript runtime


im solved this question on leetcode.com(https://leetcode.com/problems/contains-duplicate/) and the problem is my runtime was 6205ms which is very bad because 69% of users solved it with 86ms i tried a few things but nothing worked i searched but there was nothing i could do i really could use some help and explaining

let dupes = []
    for(let i=0; i<nums.length; i++){
        if(!dupes.includes(nums[i])){
            dupes.push(nums[i])
        }
    }
    return !(dupes.length == nums.length)


Solution

  • so as Barmar said in his comments i changed the array dupes to a set and changed includes to has(), length to size and push() to add() this is the code`

    let dupes = new Set()
    for(let i=0; i<nums.length; i++){
        if(!dupes.has(nums[i])){
            dupes.add(nums[i])
        }
    }
    return !(dupes.size == nums.length)