πŸ“Œ NeetCode 150: Contains Duplicate (01. Duplicate Integer)


πŸ“‹ Problem Statement

Given an integer array nums, return true if any value appears more than once in the array, otherwise return false.

Examples

Example 1:

Input: nums = [1, 2, 3, 3]
Output: true

Example 2:

Input: nums = [1, 2, 3, 4]
Output: false

Constraints

  • $0 \le \text{nums.length} \le 10

πŸ’‘ NeetCode Hints & Strategy

TIP

  • Hint 1: A brute force solution would be to check every element against every other element in the array. This would be an solution. Can you think of a better way?
  • Hint 2: Is there a way to check if an element is a duplicate without comparing it to every other element? Maybe there’s a data structure that is useful here.
  • Hint 3: We can use a hash data structure like a hash set or hash map to store elements we’ve already seen. This will allow us to check if an element is a duplicate in constant time.

πŸ‹οΈ Space to Practice

πŸ“ Step-by-Step Self-Solving Framework

  1. Understand Goal: Return true if duplicate exists, false if all numbers unique.
  2. Evaluate Constraints: brute force will TLE on large arrays.
  3. Select Data Structure: Hash Set allows insertion & lookup.
  4. Draft Pseudocode:
    seen = empty set
    for each x in nums:
        if x is in seen:
            return true
        add x to seen
    return false

πŸ’» My C# Code Scratchpad

public static bool UserSolution(int[] nums)
{
    // Write your solution here!
    return false;
}

πŸ§ͺ Test Cases & Benchmark Matrix

Case #Input numsExpected OutputTypeGoal TimeGoal Memory
1[1, 2, 3, 3]trueStandard DuplicateMinimal
2[1, 2, 3, 4]falseAll Unique set alloc
3[1, 1, 1, 3, 3, 4]trueMultiple DuplicatesEarly return
4[]falseEmpty Array
5[7]falseSingle ElementMinimal
6[-1, -2, -3, -1]trueNegative NumbersMinimal

πŸ’‘ Multi-Solution Analysis (Deep Step-by-Step Explanations)

Approach 1: HashSet (Optimal Solution) ⭐

Intuition & Concept

A Hash Set maintains unique elements with average lookup and insertion time. As we iterate through nums, we query the set to see if the element was seen previously.

Step-by-Step Solving Logic

  1. Initialize Set: Create HashSet<int> seen.
  2. Iterate Array: Loop over each integer num in nums.
  3. Add & Check: In C#, seen.Add(num) returns false if num is already present in seen.
  4. Early Exit: If seen.Add(num) returns false, return true immediately.
  5. Completion: If loop completes, return false.

C# Source Code

public static bool Reference_HashSet(int[] nums)
{
    HashSet<int> seen = new HashSet<int>();
    foreach (int num in nums)
    {
        if (!seen.Add(num)) return true;
    }
    return false;
}

Complexity Analysis

  • Time Complexity: β€” Single pass; average set insertion.
  • Space Complexity: β€” Up to elements stored in set in worst case.

Approach 2: Sorting (Alternative Solution)

Intuition & Concept

Sorting rearranges elements into ascending order. Any duplicate values will sit adjacent to each other.

Step-by-Step Solving Logic

  1. Base Case: If nums.Length <= 1, return false.
  2. Sort: Call Array.Sort(nums).
  3. Compare Neighbors: Loop from 1 to nums.Length - 1. If nums[i] == nums[i - 1], return true.
  4. Completion: Return false.

C# Source Code

public static bool Reference_Sorting(int[] nums)
{
    if (nums.Length <= 1) return false;
    Array.Sort(nums);
    for (int i = 1; i < nums.Length; i++)
    {
        if (nums[i] == nums[i - 1]) return true;
    }
    return false;
}

Complexity Analysis

  • Time Complexity: β€” Sorting dominates.
  • Space Complexity: auxiliary space if sorted in-place.

Approach 3: Brute Force (Naive Baseline)

Intuition & Concept

Compare all pairs where .

Step-by-Step Solving Logic

  1. Loop from to .
  2. Loop from to .
  3. If nums[i] == nums[j], return true.
  4. Return false.

C# Source Code

public static bool Reference_BruteForce(int[] nums)
{
    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;
}

Complexity Analysis

  • Time Complexity: β€” comparisons.
  • Space Complexity: β€” Zero extra dynamic allocation.

πŸ› οΈ C# Tips & Common Pitfalls

  1. C# HashSet.Add(x) Method:
    • seen.Add(x) returns bool (false if element already existed).
  2. Memory Overhead:
    • HashSet<int> has memory overhead per entry compared to arrays. For ultra-low memory environments, sorting is space.
  3. Shared Benchmarking:
    • Use DSA.Common.DsaTestRunner to measure execution time (ms) and thread memory allocations (Bytes) automatically!