blind-75

Contains Duplicate

Best Case: The best case is when there are no duplicates.
Worst Case: The worst case is when all elements are duplicates.

Approach:

  1. Use a set to track seen elements.
  2. If an element is already in the set during iteration, return true.

Explanation to Interviewer:
“I would utilize a set to track elements as I iterate through the array. If I encounter an element that already exists in the set, I can immediately conclude that there are duplicates.”

Code Implementation:

JavaScript:

function containsDuplicate(arr) {
    const seen = new Set();
    for (const num of arr) {
        if (seen.has(num)) {
            return true;
        }
        seen.add(num);
    }
    return false;
}

const arr = [1, 2, 3, 1];
console.log(containsDuplicate(arr)); // Output: true

Python:

def contains_duplicate(arr):
    seen = set()
    for num in arr:
        if num in seen:
            return True
        seen.add(num)
    return False

arr = [1, 2, 3, 1]
print(contains_duplicate(arr))  # Output: True