DEV Community

tracelit
tracelit

Posted on • Originally published at tracelit.dev

LeetCode 217: Contains Duplicate — Step-by-Step Visual Trace

Easy — Array | Hash Table | Hash Set | Sorting

The Problem

Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.

Approach

Use a hash set to track elements we've seen before. As we iterate through the array, check if the current element already exists in the set - if yes, we found a duplicate and return true, otherwise add it to the set.

Time: O(n) · Space: O(n)

Code

class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        hashset = set()

        for n in nums:
            if n in hashset:
                return True
            hashset.add(n)
        return False
Enter fullscreen mode Exit fullscreen mode

Watch It Run

Watch the algorithm run step by step

Watch the algorithm run step by step

Open interactive visualization

Try it yourself: Open TraceLit and step through every line.


Built with TraceLit — the visual algorithm tracer for LeetCode practice.

Top comments (0)