Framework Thinking - Neetcode 150 - Contains Duplicate

1. Understand the problem that you solved:

  • We need to determine if an array contains any duplicate elements.

  • If any value appears at least twice, return True; otherwise, return False.

  • Take a moment to clarify the input and output expectations.

2. Ask clarify questions

  • What is the range and size of the array? (e.g., up to 10⁵ elements?)

  • Can numbers be negative?

  • Should the output be a boolean?

  • What time complexity is expected — O(n), O(n log n), or O(n²) is acceptable?

  • What should we return for an empty array? (Usually False)

3. Work through examples

Example 1: nums = [1,2,3,1] → duplicate 1 → True

Example 2: nums = [1,2,3,4] → no duplicates → False

Example 3: nums = [] → no duplicates → False

Example 4: nums = [0, -1, -1] → duplicate -1 → True

4. Brainstorm 2–3 solutions

  1. Naive solution (O(n²) time, O(1) space):
  • Use two loops to compare every pair. Too slow for large input.
  1. Optimized solution (O(n log n) time, O(1) space):
  • Sort the array and check if adjacent elements are equal.
  1. Most optimized (O(n) time, O(n) space):
  • Use a set to track seen elements. If element already in set → duplicate found.

5. Implement Solution

5.1. Brute Force

class Solution:
    def hasDuplicate(self, nums: List[int]) -> bool:
        for i in range(len(nums)):
            for j in range(i + 1, len(nums)):
                if nums[i] == nums[j]:
                    return True
        return False
  • Time Complexity: O(N^2).

  • Space Complexity: O(1).

5.2. Sorting

class Solution:
    def hasDuplicate(self, nums: List[int]) -> bool:
        nums.sort()
        for i in range(1, len(nums)):
            if nums[i] == nums[i - 1]:
                return True
        return False
  • Time Complexity: O(NlogN).

  • Space Complexity: O(1).

5.3. Hash Set

class Solution:
    def hasDuplicate(self, nums: List[int]) -> bool:
        seen = set()
        for num in nums:
            if num in seen:
                return True
            seen.add(num)
        return False
  • Time Complexity: O(N).

  • Space Complexity: O(N).

5.4. Hash Set Length

class Solution:
    def hasDuplicate(self, nums: List[int]) -> bool:
        return len(set(nums)) < len(nums)
  • Time Complexity: O(N).

  • Space Complexity: O(N).

6. Test your code

Dry run example:


nums = [1,2,3,1]

seen = {}

n = 1  add {1}

n = 2  add {1,2}

n = 3  add {1,2,3}

n = 1  already in set  return True

  • ✅ Works for all cases.

  • Time: O(n), Space: O(n)

Last Updated On October 25, 2025