Algorithms and Data Structures · Junior · Question 17 of 75
How do you check in O(n) whether an array contains duplicates?
- 1Call
indexOffor every element - ✓Correct answer: Walk the array once and track seen values in a
Set - 3Compare every pair of elements with two nested loops
Explanation
One pass with a Set: if seen.has(x) is already true, there's a duplicate. Nested loops and indexOf inside a loop are both O(n²).