Contains Duplicate - LeetCode Problem

Contains Duplicate - LeetCode Problem

Problem Description

The "Contains Duplicate" problem is a classic LeetCode problem that asks you to determine if an array contains any duplicates. Given an integer array nums, the problem asks us to return true if any value appears at least twice in the array, and return false if every element is distinct.

Solution

The most straightforward solution to this problem is to use a hash set. We can loop through the array, adding each element to the hash set. If we come across an element that is already in the hash set, we know that the array contains a duplicate and we can return true. If we make it through the entire array without finding a duplicate, we can return false.

Here's the code for the solution:

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

        for num in nums:
            if num in seen:
                return True
            seen.add(num)
        return False

Complexity Analysis

The time complexity of this solution is O(n), where n is the length of the array. We need to loop through the entire array once, and each hash set lookup takes O(1) time on average.

The space complexity of this solution is also O(n). In the worst case, every element in the array is unique, and we need to store them all in the hash set.

Conclusion

The "Contains Duplicate" problem is a great example of how hash sets can be used to efficiently solve a problem. With just a few lines of code, we can check whether an array contains any duplicates in linear time. As a beginner, it's important to learn about hash sets and their properties, as they are a fundamental data structure used in many algorithms and programming problems. Happy coding! 😎