Finding Duplicates
DSA · Arrays & Stringssyntax
Approach 1: Hash set — O(n) time, O(n) space
Approach 2: Sort first — O(n log n) time, O(1) space
Approach 3: Floyd's cycle (special constraints) — O(n) time, O(1) spaceexample
// JavaScript — Hash set approach
function containsDuplicate(arr) {
const seen = new Set();
for (const val of arr) {
if (seen.has(val)) return true;
seen.add(val);
}
return false;
}
function findDuplicate(arr) {
// Values in range [1, n], exactly one duplicate
const seen = new Set();
for (const val of arr) {
if (seen.has(val)) return val;
seen.add(val);
}
}
# Python
def contains_duplicate(arr):
seen = set()
for val in arr:
if val in seen:
return True
seen.add(val)
return False
def find_duplicate(arr):
seen = set()
for val in arr:
if val in seen:
return val
seen.add(val)output
contains_duplicate([1,2,3,1]) → True
find_duplicate([1,3,4,2,2]) → 2Note The hash set approach is the go-to. If asked for O(1) space with values in [1,n], use Floyd's tortoise and hare or index marking (negate values). Always clarify constraints: can you modify the input? What is the value range?