LC #217: Contains Duplicate

2 min read
๐ง Problem Statement
Check if any element appears more than once in the array.
๐ Leetcode Link
๐ฅ Brute Force
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] == nums[j]) return true;
}
}
return false;
- Time: O(nยฒ) โ nested loop
- Space: O(1)
โ Works, but super slow for big inputs.
โก Optimized: HashSet FTW
Set<Integer> seen = new HashSet<>();
for (int num : nums) {
if (seen.contains(num)) return true;
seen.add(num);
}
return false;
- Time: O(n)
- Space: O(n)
๐ก Why better? Because .contains()
and .add()
in HashSet = O(1) time.
๐งช Test Case 1: Duplicate Present
Input: [1, 2, 3, 1]
Expected Output: true
๐ Dry Run:
- seen =
{}
1
โ not seen โ add โ{1}
2
โ not seen โ add โ{1,2}
3
โ not seen โ add โ{1,2,3}
1
โ already seen โ returntrue
๐งช Test Case 2: All Unique
Input: [10, 20, 30, 40]
Expected Output: false
๐ Dry Run:
- seen =
{}
10
โ not seen โ add โ{10}
20
โ not seen โ add โ{10,20}
30
โ not seen โ add โ{10,20,30}
40
โ not seen โ add โ{10,20,30,40}
- Done โ return
false
๐ Similar Problems
- LeetCode #219 โ Contains Duplicate II (within k indices)
- LeetCode #3 โ Longest Substring Without Repeating Characters (sliding window)
0
Subscribe to my newsletter
Read articles from LilSardarX directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

LilSardarX
LilSardarX
Iโm figuring things out in tech โ and blogging along the way. I write what I learn, so I can revise it later and maybe help you avoid a few rabbit holes.