Contains Duplicate

Difficulty: Easy

Given a list of numbers, return true if any value appears more than once, and false if every number is unique.

Examples

Input: nums = [1, 2, 3, 1]
Output: true

The value 1 appears twice - once at index 0 and again at index 3.

Input: nums = [1, 2, 3, 4]
Output: false

Every number appears exactly once.

Input: nums = [1, 1, 1, 3, 3, 4, 3, 2, 4, 2]
Output: true

Several values (1, 3, 4, 2) each repeat.

Constraints

  • 1 <= nums.length <= 10^5

  • -10^9 <= nums[i] <= 10^9

Approach

The obvious approach compares each number against every other number. It works, but repeats a lot of comparisons.

Sorting first is better: duplicates end up next to each other, so one pass checking neighbors catches a repeat.

The fastest approach skips sorting. Walk the list once, keeping a hash set of values seen so far. If a number is already in the set, you've found a duplicate.

Solutions

Brute Force - Check Every Pair

Compare every number against every number after it. If any pair matches, there's a duplicate. Simple, but it checks every pair, so it gets slow as the list grows.

function containsDuplicate(nums) {
  for (let i = 0; i < nums.length; i++) {
    for (let j = i + 1; j < nums.length; j++) {
      if (nums[i] === nums[j]) {
        return true;
      }
    }
  }
  return false;
}

Time: O(n²) · Space: O(1)

Better - Sort First

Sort a copy of the list. Equal values are then next to each other, so one pass comparing each element to its neighbor finds any duplicate.

function containsDuplicate(nums) {
  const sorted = [...nums].sort((a, b) => a - b);

  for (let i = 1; i < sorted.length; i++) {
    if (sorted[i] === sorted[i - 1]) {
      return true;
    }
  }

  return false;
}

Time: O(n log n) · Space: O(n)

Optimal - Hash Set

Walk the list once. If a number is already in the hash set of seen numbers, you've found a duplicate. If not, add it and keep going.

function containsDuplicate(nums) {
  const seen = new Set();

  for (const num of nums) {
    if (seen.has(num)) {
      return true;
    }
    seen.add(num);
  }

  return false;
}

Time: O(n) · Space: O(n)