⚡ TL;DR
Solve Contains Duplicate in Dart with working code. Hash Set (Optimal) approach with O(n) time, plus complexity analysis and interview tips.
Contains Duplicate (#217 — Easy): 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.
Problem Statement
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:
Input: nums = [1,2,3,1]
Output: trueApproach: Hash Set (Optimal)
Time: O(n) | Space: O(n)
A hash set rejects duplicate insertions. In Python, comparing lengths of list vs set is the idiomatic one-liner.
bool containsDuplicate(List<int> nums) {
final seen = <int>{};
for (final num in nums) {
if (!seen.add(num)) return true;
}
return false;
}
void main() {
print(containsDuplicate([1,2,3,1])); // true
print(containsDuplicate([1,2,3,4])); // false
}Key Takeaways
- Start with the brute-force approach to understand the problem
- Hash Set (Optimal) gives the optimal O(n) solution
- Practice this pattern — it appears frequently in coding interviews
Related Problems
- Contains Duplicate in Python
- Contains Duplicate in Go
- Contains Duplicate in Swift
- Two Sum in Dart
- Remove Duplicates from Sorted Array in Dart
- Maximum Subarray in Dart
FAQ
What is the best approach to solve Contains Duplicate in Dart?
The recommended approach is Hash Set (Optimal), which runs in O(n) time with O(n) space. The full Dart implementation is shown above.
What is the time complexity of Contains Duplicate in Dart?
Using Hash Set (Optimal), the time complexity is O(n) and the space complexity is O(n).
Happy coding!
