Contains Duplicate – Detailed Python Explanation
Problem Statement
Given an integer array nums, return True if any value appears at least twice in the array, and return
False if every element is distinct.
Examples
Input: nums = [1, 2, 3, 1] → Output: True
Input: nums = [1, 2, 3, 4] → Output: False
Constraints (as used in interview problems)
• 1 ≤ len(nums) ≤ 10■
• -10■ ≤ nums[i] ≤ 10■
Core Intuition
The goal is to quickly determine whether a number has appeared before. Checking duplicates efficiently
requires fast lookups, which makes sets ideal.
Approach 1: Using a Set (Primary Strategy)
We iterate through the array while storing visited elements in a set. If an element already exists in the
set, we immediately know a duplicate is present.
Algorithm Steps
1. Initialize an empty set called seen.
2. Traverse each number in the array.
3. If the number exists in seen, return True.
4. Otherwise, add the number to seen.
5. If no duplicates are found, return False.
Python Code (Step-by-Step)
def containsDuplicate(nums): seen = set() for num in nums: if num in seen: return
True [Link](num) return False
Explanation: The set keeps track of previously seen values. Membership checks in a set are very fast,
making this solution optimal.
Dry Run Example
Input: [1, 2, 3, 1]
seen = {} → add 1
seen = {1} → add 2
seen = {1, 2} → add 3
seen = {1, 2, 3} → 1 already exists → return True
Approach 2: Length Comparison Trick
A set automatically removes duplicate elements. If the length of the set is smaller than the length of the
original array, duplicates must exist.
Python Code (One-Liner)
def containsDuplicate(nums): return len(nums) != len(set(nums))
Time & Space Complexity
Time Complexity: O(n) — each element is processed once.
Space Complexity: O(n) — extra space for the set.
What Not to Do
Avoid comparing every element with every other element using nested loops. Such approaches are
inefficient and not suitable for large inputs.
Final Interview Takeaway
This problem tests your understanding of hash-based data structures. Using a set is the cleanest and
most efficient Python solution.