Contains Duplicate – Solution & Complexity
1. Understand the Problem
- We need to decide whether any value appears more than once.
- The exact duplicate value does not need to be returned, only
TrueorFalse. - An empty or fully distinct list should return
False.
2. Consider the Brute Force Idea
- A direct approach compares every pair of numbers.
- If any pair has the same value, we found a duplicate.
- This works, but checking all pairs takes O(n²) time.
3. Use a Set for Fast Lookups
- A set can tell us in average O(1) time whether we have seen a number before.
- Scan the array once from left to right.
- When a number is already in the set, return
Trueimmediately.
4. Build the Check Incrementally
- Keep a
seenset. - For each number, check membership before adding it.
- If the loop finishes, every number was distinct.
5. Final Solution and Complexity
- The final solution returns as soon as a duplicate is found.
- Time complexity is O(n) because each element is processed once.
- Space complexity is O(n) in the worst case for the set of seen values.