Exercise 6: Check if Array Contains Duplicates
Problem Statement
Create a function `hasDuplicates(arr)` that checks if array contains duplicates.
Example:
- hasDuplicates([1, 2, 3, 2]) → true
- hasDuplicates([1, 2, 3]) → false
Sample Output:
hasDuplicates([1, 2, 3, 2]) => true hasDuplicates([1, 2, 3]) => false hasDuplicates(["a", "b", "a"]) => true
Solution
const hasDuplicates = (arr) => {
const seen = new Set();
for (const item of arr) {
if (seen.has(item)) return true;
seen.add(item);
}
return false;
};Explanation
Overall Goal:
- Array me duplicates check karna efficiently.
- Set data structure use karke O(n) time complexity.
Line 1: Function header
const hasDuplicates = (arr) => {
Line 2: Track seen items
const seen = new Set();- Set fast lookup deta hai (O(1)).
Line 3: Iterate array
for (const item of arr)
Line 4: Check duplicate
if (seen.has(item)) return true;- Agar pehle dekha hai to duplicate hai.
Line 5: Mark as seen
seen.add(item);
Real world:
- Form validation: duplicate emails/usernames.
- Data processing: duplicate detection.