Overview
Given an array of integers, determine whether any value appears at least twice. Return true if any duplicate exists, false if every element is distinct.
Implement hasDuplicates(nums).
Constraints
- Input is always an array of numbers (may be empty).
- An empty array and a single-element array return
false. - Must handle negative numbers and zero.
- Aim for $O(n)$ time complexity.
Examples
hasDuplicates([1, 2, 3, 1]); // true — 1 appears twice hasDuplicates([1, 2, 3, 4]); // false — all distinct hasDuplicates([]); // false hasDuplicates([1, 1, 1, 3, 3, 4]); // true
Notes
- A Set-based approach gives $O(n)$ time: iterate and check membership before inserting.
- Alternatively, sort first ($O(n \log n)$) and scan for adjacent duplicates — but this mutates the input.
- Watch for the early-exit optimization: return
trueas soon as you find the first duplicate.
Solution
Reveal solution
function hasDuplicates(nums) {
const seen = new Set();
for (const n of nums) {
if (seen.has(n)) return true;
seen.add(n);
}
return false;
}Resources
find-duplicates-in-array.js
Find Duplicates in Array
easycodingAlgorithmsData Structures
Overview
Given an array of integers, determine whether any value appears at least twice. Return true if any duplicate exists, false if every element is distinct.
Implement hasDuplicates(nums).
Constraints
- Input is always an array of numbers (may be empty).
- An empty array and a single-element array return
false. - Must handle negative numbers and zero.
- Aim for $O(n)$ time complexity.
Examples
hasDuplicates([1, 2, 3, 1]); // true — 1 appears twice hasDuplicates([1, 2, 3, 4]); // false — all distinct hasDuplicates([]); // false hasDuplicates([1, 1, 1, 3, 3, 4]); // true
Notes
- A Set-based approach gives $O(n)$ time: iterate and check membership before inserting.
- Alternatively, sort first ($O(n \log n)$) and scan for adjacent duplicates — but this mutates the input.
- Watch for the early-exit optimization: return
trueas soon as you find the first duplicate.
Solution
Reveal solution
function hasDuplicates(nums) {
const seen = new Set();
for (const n of nums) {
if (seen.has(n)) return true;
seen.add(n);
}
return false;
}Resources
NameTopicDifficulty
103 of 103 problems