Skip to content
Problem · Canonical Warm-Up
easyset · hash · sortingTime · O(n)Space · O(n)

Contains Duplicate

Problem statement

Statement

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

Examples

nums = [1, 2, 3, 1]
-> true              (1 appears at index 0 and index 3)

nums = [1, 2, 3, 4]
-> false             (all four values are distinct)

nums = [1, 1, 1, 3, 3, 4, 3, 2, 4, 2]
-> true              (the duplicate is found at index 1, on the second read)

nums = [7]
-> false             (a single element cannot repeat)

Constraints

  • 1 <= len(nums) <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • The array is unsorted and may be mutated unless the interviewer says otherwise.

What this problem is really testing

Almost nobody fails to solve this. The interviewer is not checking whether you can detect a repeat; they are checking whether you can talk about the cost of remembering. There are exactly three defensible answers here and each one buys a different resource: nested loops spend time to save memory, sorting spends a log factor and destroys the input to save memory, and a hash set spends memory to save time. A candidate who writes the hash set without naming the trade has answered the coding question and missed the engineering one.

The useful mental model is a door with a guest list. A bouncer who remembers every face that walked in recognises a repeat instantly, but their memory grows with the crowd. A bouncer who instead makes everyone queue in alphabetical order can spot repeats by glancing at neighbours and needs no memory at all, but the queueing itself costs time and rearranges the crowd. Both bouncers are correct. Which one you want depends on whether the club is short on time or short on brain. State which one you picked and why, and the rest of the problem is mechanical.

The second thing under test is the early exit. The set solution returns the moment it sees a repeat, so on the input [1, 1, 1, ...] with a hundred thousand elements it reads two of them. The idiomatic Python one-liner does not: it consumes the entire array first. Both are O(n) in the worst case and they behave very differently in the average case, which is exactly the kind of distinction a follow-up question is built on.