From 6d0b022c8fe3020c4b9a2599c9f9e085065bbf66 Mon Sep 17 00:00:00 2001 From: Yerim Moon Date: Mon, 2 Mar 2026 16:03:57 -0800 Subject: [PATCH] contains duplicate solution --- contains-duplicate/yerim01.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 contains-duplicate/yerim01.py diff --git a/contains-duplicate/yerim01.py b/contains-duplicate/yerim01.py new file mode 100644 index 0000000000..f9dbb86d7d --- /dev/null +++ b/contains-duplicate/yerim01.py @@ -0,0 +1,22 @@ +# Leetcode 217: https://leetcode.com/problems/contains-duplicate/description/ +# Goal: Given an array of integers, +# return True if the array has duplicates or return False if all elements are distinct. +# Approach: +# - Use a hash set to track elements we have already seen. +# - Iterate through the array and if the current number already exists in the set, return True. +# - Otherwise, add the current number to the set. +# Time complexity: O(n) +# - We iterate through the array once. +# Space complexity: O(n) +# - We store all elements in the set in the worst case. + +class Solution: + def containsDuplicate(self, nums: List[int]) -> bool: + h = set() + + for n in nums: + if n not in h: + h.add(n) + else: + return True + return False