Tom on the Internet
← Back

Contains Duplicate

easy
Array Hash Table

<Code />

function hasDuplicate(nums) {
    let s = new Set();
    for (let n of nums) {
        if (s.has(n)) {
            return true;
        }
        s.add(n);
    }
    return false;
}

Thoughts

To find if there are duplicats in a list, the most natural solution, to me, is to sort the list and then check if any two adjacent elements are the same. But, that's not the most efficient solution because sorting is O(n log n). A more efficient solution is to use a hash set. As you iterate through the list, you can check if the element is already in the set. If it is, then you have a duplicate. If not, add it to the set. This solution is O(n) because you only iterate through the list once.