Skip to content
PlaceNivo

Hashing Easy

Contains Duplicate: Solution and Approach

Return true if any value appears at least twice in the array, and false if every element is distinct.

Similar questions reported in: TCS, Accenture, Capgemini, Cognizant

Example

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

Brute force first

Compare every pair: O(n²). Sorting and checking neighbours is O(n log n).

The better idea

Keep a hash set of values already seen. If the current value is already in the set, you have found a duplicate.

Steps

  1. Create an empty set.
  2. For each number: if it is in the set, return true. Otherwise add it.
  3. Return false after the loop.

Code

def contains_duplicate(nums):
    seen = set()
    for x in nums:
        if x in seen:
            return True
        seen.add(x)
    return False

Complexity

Time: O(n) on average.

Space: O(n) for the set.

Edge cases to test

  • An empty array or a single element: return false.
  • Negative numbers work the same way.

Solved it? Pick the next problem

Do one more problem from the same pattern today, so the idea sticks.