Skip to main content

25. Contains Duplicate

easyAsked at Glassdoor

Deduplicating reviews before they're stored is one of Glassdoor's first data-quality gates — this Set-based duplicate-detection problem is their simplest warmup and a signal that you know O(n) beats sort-based O(n log n).

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given an integer array nums, return true if any value appears at least twice, and false if every element is distinct.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9

Examples

Example 1

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

Explanation: 1 appears at index 0 and index 3.

Example 2

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

Approaches

1. Sort then scan

Sort the array so duplicates become adjacent, then check consecutive elements. O(n log n) time, O(1) extra space if sort is in-place.

Time
O(n log n)
Space
O(1)
function containsDuplicate(nums) {
  nums.sort((a, b) => a - b);
  for (let i = 1; i < nums.length; i++) {
    if (nums[i] === nums[i - 1]) return true;
  }
  return false;
}

Tradeoff:

2. Hash set — single pass

Insert each element into a Set. If it's already present, a duplicate exists. O(n) time, O(n) space.

Time
O(n)
Space
O(n)
function containsDuplicate(nums) {
  const seen = new Set();
  for (const n of nums) {
    if (seen.has(n)) return true;
    seen.add(n);
  }
  return false;
}

Tradeoff:

Glassdoor-specific tips

Glassdoor keeps this problem in the warmup rotation precisely because the tradeoff discussion matters more than the code. They want to hear you articulate why you're choosing O(n) space for O(n) time versus the sort approach that trades time for space. Mention early termination: the Set version can return true as soon as it finds the first duplicate, without scanning the rest of the array — a real advantage when duplicates appear early.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Contains Duplicate and other Glassdoor interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →