contains_duplicate

Solution

	
	"""
https://leetcode.com/problems/contains-duplicate/description/

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.
"""

from typing import List


def contains_duplicate(arr: List[int]) -> bool:
    """
    one-liner:
    return len(set(arr)) != len(arr)
    """
    hash = set()
    for i in arr:
        if i in hash:
            return True
        hash.add(i)
    return False

	

Tests

	
	from publicmatt.leet.problems.contains_duplicate import contains_duplicate


def test_small_duplicate():
    nums = [1, 2, 3, 1]
    assert contains_duplicate(nums)


def test_no_dup():
    nums = [1, 2, 3, 4]
    assert not contains_duplicate(nums)


def test_large_multi_dup():
    nums = [1, 1, 1, 3, 3, 4, 3, 2, 4, 2]
    assert contains_duplicate(nums)

	
contains_duplicate