LC #217: Contains Duplicate

LilSardarXLilSardarX
2 min read

๐Ÿง  Problem Statement

Check if any element appears more than once in the array.

Contains Duplicate - LC #217


๐Ÿ’ฅ 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 โ†’ return true

๐Ÿงช 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

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.