Best Case: The best case is when there are no duplicates.
Worst Case: The worst case is when all elements are duplicates.
Approach:
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