Contains Duplicate

25 min · containsDuplicate()

A repeated order ID can turn one shipment into two. Your first job is to catch the repeat.

A duplicate is a value that appears in more than one position. Given an integer array nums, return true when it contains a duplicate; return false when every value appears exactly once.

A few ground rules:

  • Equal values at different positions count as a duplicate.
  • The values may be negative, zero, or positive.
  • You only need to decide whether a repeat exists, so you may stop as soon as you find one.

Constraints

  • 1 <= nums.length <= 100_000
  • -1_000_000_000 <= nums[i] <= 1_000_000_000

Hints

Start with every pair

Pick one position and compare it with every later position. That works, but how many comparisons does an array of 100,000 distinct values force you to make?

Remember the past

A hash set is a collection that stores unique values and supports fast membership checks. While scanning, it can answer: "have I seen this value before?"

Check before adding

For each value, check the set first. If the value is present, return true; otherwise, add it and continue. Reaching the end means every value was new.

Follow-up

Could your approach detect a duplicate while the numbers arrive as a stream, without storing the entire input array?

Visible cases

Examples

Example 1

ready
Input
nums = [
  14,
  3,
  8,
  14
]
Expected
true
Why
14 appears at both ends

Example 2

ready
Input
nums = [
  7,
  -2,
  9,
  4
]
Expected
false
Why
every value appears exactly once

Example 3

ready
Input
nums = [
  5,
  5,
  8,
  10
]
Expected
true
Why
the repeat is visible after one step

Interview signal

Asked at

AmazonAppleMicrosoft
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite