100 Days LeetCode — Day 1
Day 1 of my 100 Days LeetCode challenge — solving "Contains Duplicate" with two approaches: sorting and HashSet.
Starting this 100 Days LeetCode challenge to sharpen my problem-solving skills for coding interviews. Arrays are the most fundamental data structure — and "Contains Duplicate" is a great first problem to practice two core patterns: sorting and hash-based lookups.
Contains Duplicate
Description
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.
Examples:
Example 1:
Input: nums = [1, 2, 3, 1]
Output: true
Example 2:
Input: nums = [1, 2, 3, 4]
Output: false
Example 3:
Input: nums = [1, 1, 1, 3, 3, 4, 3, 2, 4, 2]
Output: true
Constraints:
1 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9
🔗 LeetCode 217 — Contains Duplicate
Approach 1 — Sorting
Idea: Sort the array first. If two numbers are the same, they will be placed next to each other. Then we just need to check whether any two adjacent numbers are equal.
class Solution {
public boolean containsDuplicate(int[] nums) {
Arrays.sort(nums);
for (int i = 1; i < nums.length; i++) {
if (nums[i] == nums[i - 1]) {
return true;
}
}
return false;
}
}
Complexity:
| Value | Explanation | |
|---|---|---|
| Time | O(n log n) | Sorting (O(n log n)) + linear scan (O(n)) |
| Space | O(1) | In-place sort, no extra data structure |
Approach 2 — HashSet
Idea: Create a HashSet and add each element from the nums array. If add() returns false, the element already exists — we found a duplicate.
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> seen = new HashSet<>();
for (int num : nums) {
if (!seen.add(num)) {
return true;
}
}
return false;
}
}
Complexity:
| Value | Explanation | |
|---|---|---|
| Time | O(n) | Single pass through the array |
| Space | O(n) | HashSet stores up to n elements |
Comparison
| Approach | Time | Space | Trade-off |
|---|---|---|---|
| Sorting | O(n log n) | O(1) | Slower but uses no extra memory |
| HashSet | O(n) | O(n) | Faster but uses extra memory |
Tip: In interviews, mention both approaches and explain the time-space trade-off. The HashSet approach is usually preferred for its linear time complexity.
Thanks for reading! If you're also preparing for coding interviews, check out my SOLID Principles and JVM Memory Tuning posts. 🚀