AceYourInterviews
Checking sign-in…

2. Contains Duplicate

FoundationHash-set membership and processed-prefix state

Decide whether the array contains the same integer at two or more different positions. You only need to report whether a duplicate exists; you do not need to list duplicate values or count their occurrences.

An empty array and an array containing only distinct values both produce false. The order in which values appear does not change the answer.

Example 1

Input

[1,2,3,1]

Output

true

Explanation: The first and last positions hold the same value.

Example 2

Input

[1,2,3,4]

Output

false

Explanation: Every value is distinct.

Example 3

Input

[-2147483648,2147483647,-2147483648]

Output

true

Explanation: Extreme signed values are ordinary set keys; no subtraction is needed.

Constraints

  • 0 <= nums.length <= 105
  • -231 <= nums[i] <= 231 - 1
Hints
Hint 1

Which fact about the past does the next value need?

Hint 2

Store distinct values already processed.

Hint 3

An insertion that does not add a new value proves a duplicate.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

A nonadjacent repeat

[1,2,3,1]
true