Skip to content
DSA Patterns
Menu
Language
HashingLC #2174 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Contains Duplicate

Problem (restated)

Return true if any value appears at least twice in the array.

Intuition

A set remembers seen values; a second sighting is a duplicate.

Approaches

Hash set

Unverified
Time O(n)Space O(n)

Idea. Insert each number into a set; if already present, return true.

Walkthrough. [1,2,3,1] → see 1 again → true.

Trade-offs. Sorting is O(n log n) with O(1) extra space if allowed to mutate.

Solution
export function containsDuplicate(nums: number[]): boolean {
  const seen = new Set<number>();
  for (const x of nums) {
    if (seen.has(x)) return true;
    seen.add(x);
  }
  return false;
}
export function containsDuplicate(nums: number[]): boolean {
  const seen = new Set<number>();
  for (const x of nums) {
    if (seen.has(x)) return true;
    seen.add(x);
  }
  return false;
}

Template connection

Insert each value into a set. A value that is already present is a duplicate, so the answer is true. An empty array, and an array of unique values, answer false.

Reflection

  • “At least twice” is a set. Sorting and comparing neighbors is O(n log n).
  • Are the empty array and a single element both false?
  • What happens if you insert first and only then ask whether the value was already present?
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Contains duplicate: true iff any value appears twice. Scan once with a set.

1
0
2
1
3
2
1
3
map{ }

seen = {}

Key:CurrentActive rangeMatchSettled