InterviewPrepKit

Home / Coding / Arrays & Hashing

Contains Duplicate

easy Original β†—
Solving tips
  • A question about pairs of positions ('any two equal?') becomes a membership question, which a hash set answers in O(1).
  • Walk once, returning True on the first value already in the set; this short-circuits, unlike len(set(nums)) < len(nums).
  • Target O(n) time and O(n) space; sorting then comparing neighbors is the O(n log n), O(1)-extra alternative when memory is tight.
  • Avoid the O(n^2) double loop, and use sorted(nums) rather than nums.sort() to avoid mutating the caller's list.

Problem

Given an integer array nums, return True if any value appears more than once in the array, and False if every element is distinct.

Examples

  • nums = [1,2,3,1] β†’ True β€” the value 1 appears at indices 0 and 3.
  • nums = [1,2,3,4] β†’ False β€” all four values are distinct.
  • nums = [1,1,1,3,3,4,3,2,4,2] β†’ True β€” several values repeat (1, 3, 4, 2).

Constraints

  • 1 <= len(nums) <= 10^5
  • -10^9 <= nums[i] <= 10^9

At 10^5 elements, an O(n^2) pairwise comparison is about 5 * 10^9 operations β€” you need O(n log n) or better.

Think about it first

Hint 1 The naive answer compares every pair of elements. How many pairs is that for 10^5 elements?
Hint 2 If the array were sorted, where would any duplicates have to sit relative to each other?
Hint 3 A hash set gives O(1) membership checks. Walk the array once, asking "have I seen this value before?" and recording each value as you go.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.