LeetCode 217: Contains Duplicate Solution
Master LeetCode problem 217 (Contains Duplicate), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
217. Contains Duplicate
Problem Explanation
Explanation
To solve this problem, we can use a HashSet data structure to store unique elements as we iterate through the input array. If we encounter an element that is already present in the HashSet, we return true as it indicates a duplicate. If we finish iterating without finding any duplicates, we return false.
- We iterate through the array once, adding each element to the HashSet and checking for duplicates.
- Time complexity: O(n) where n is the number of elements in the array.
- Space complexity: O(n) in the worst case where all elements are unique.
Solution Code
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int num : nums) {
if (!set.add(num)) {
return true;
}
}
return false;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 217 (Contains Duplicate)?
This page provides optimized solutions for LeetCode problem 217 (Contains Duplicate) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 217 (Contains Duplicate)?
The time complexity for LeetCode 217 (Contains Duplicate) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 217 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 217 in Java, C++, or Python.