CodingNodes / Arrays & Hashing / Contains Duplicate System design Space play · ←→ step · R restart

Problem

You are given a list of integers nums. Decide whether any value occurs at least twice.

Return true if some number is repeated anywhere in the list, and false if every number is different from all the others.

Constraints

  • 1 ≤ nums.length ≤ 10⁵
  • −10⁹ ≤ nums[i] ≤ 10⁹

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(n)

Time: Each number is checked against the set and added once, and both take O(1) on average.

Space: In the worst case every number is different and all n of them end up in the set.

Walk through the list and remember every number in a set. If the next number is already in the set, it is a repeat and we can stop right away.