https://leetcode.com/problems/contains-duplicate/description/
leetcode #interview
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.
Example 1:
Input: nums = [1,2,3,1]
Output: true
Explanation:
The element 1 occurs at the indices 0 and 3.
Example 2:
Input: nums = [1,2,3,4]
Output: false
Explanation:
All elements are distinct.
Example 3:
Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true
Constraints:
1 <= nums.length <= 105
-109 <= nums[i] <= 109
Here’s how you can solve the problem using Python. You can leverage the properties of sets to check for duplicates efficiently:
Explanation:
- Initialize a set:
seen = set()
. Sets in Python do not allow duplicate values, which makes them useful for checking whether an element has already been seen. - Iterate through
nums
: For each number in the input listnums
, check if it already exists in theseen
set. - Check for duplicates:
- If
num
is already inseen
, it means we’ve encountered a duplicate, so returnTrue
. - If not, add
num
to theseen
set.
- If
- If we iterate through the entire list without finding a duplicate, return
False
.
Time Complexity:
- The time complexity is O(n), where n is the number of elements in the list. Checking and inserting into a set both have an average time complexity of O(1).
Space Complexity:
- The space complexity is O(n) because, in the worst case, we might need to store all elements of the input list in the set.
This solution efficiently checks for duplicates using sets and is well-suited for the given constraints.