Contains Duplicate

Solution

class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        seen = set()
        for n in nums:
            if n in seen:
                return True
            seen.add(n)
        return False

Idea

Set lookup and insert are O(1) on average, so one pass with a seen set replaces the nested loop. It exits on the first duplicate.

Complexity

Time O(N), space O(N).


Related: LeetCode, Arrays and Hashing, Concatenation of Array, Score of a String