Skip to content
LEETFLIX

Easy · hash-set seen. Real solution for this problem — same player as the hand-authored deep-dives.

01

Problem

Read the prompt, flip through the examples, then steal the idea.

LeetCode 217. Contains Duplicate. The copyrighted prompt is on LeetCode. This page is a working hash-set seen for this problem: editable input, Python, Go, and a step-by-step animation.

Constraints

  • —Player inputs are capped so the animation stays readable.
  • —Match LeetCode's own constraints when you submit there.

Examples

Input

nums =
[1, 2, 3, 1]

Output

true

02

Solution

Python and Go. The walkthrough below runs this same code.

Approach 1Optimal▶ Animated

One-pass hash set

Remember every value. A hit means a duplicate.

A set answers “have I seen this?” in expected O(1). Insert after the lookup so a value never pairs with itself.

Algorithm

  1. Empty set seen.
  2. For each x, if x is in seen return true; otherwise insert it.
  3. If the walk finishes, return false.
Time
O(n)
Space
O(n)
Solution.py
class Solution:    def containsDuplicate(self, nums: list[int]) -> bool:        seen: set[int] = set()        for x in nums:            if x in seen:                return True            seen.add(x)        return False
Watch this run

03

Interactive walkthrough

Playing “One-pass hash set”. Edit the input, hit Run, then scrub.

Approach: One-pass hash set

Loading animation…