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

Watch It Run

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


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


Comments