Contains Duplicate
Problem Statement
Section titled “Problem Statement”Given an integer array nums, return true if any value appears at least twice, and false if every element is distinct.
Examples
Section titled “Examples”| Input | Output | Explanation |
|---|---|---|
[1, 2, 3, 1] | true | 1 appears at indices 0 and 3 |
[1, 2, 3, 4] | false | All elements are distinct |
[1, 1, 1, 3, 3, 4, 3, 2, 4, 2] | true | Multiple duplicates present |
Constraints
Section titled “Constraints”1 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9
Real-World Applications
Section titled “Real-World Applications”Complexity Comparison
Section titled “Complexity Comparison”| Approach | Time | Space | Best When |
|---|---|---|---|
| Hash Set | O(n) | O(n) | General case — fast lookup, stop early on first duplicate |
| Sorting | O(n log n) | O(1) | Memory is constrained and you can afford extra time |
Which approach should you learn first?
Section titled “Which approach should you learn first?”- Pick Hash Set for interviews — O(n) with early exit is the expected answer.
- Pick Sorting if you need to understand the space trade-off or the interviewer bans extra memory.
Approach 1: Hash Set
Section titled “Approach 1: Hash Set”Scan the array once. For each number, check if it is already in the set. If yes, return true immediately. Otherwise add it to the set and continue. A hash set gives O(1) average lookup and insert.
Step-by-step Example
Section titled “Step-by-step Example”Input: [1, 2, 3, 1]
| Step | num | In seen? | seen after |
|---|---|---|---|
| 1 | 1 | No | {1} |
| 2 | 2 | No | {1, 2} |
| 3 | 3 | No | {1, 2, 3} |
| 4 | 1 | Yes → return true | — |
Animated walkthrough
Use Next or Autoplay to see each number checked against the set and either stored or flagged as a duplicate.
Pseudocode
Section titled “Pseudocode”function containsDuplicate(nums): seen = {} for num in nums: if num in seen: return true seen.add(num) return falseSolution Code
Section titled “Solution Code”from typing import List
def contains_duplicate(nums: List[int]) -> bool: seen = set() for num in nums: if num in seen: return True seen.add(num) return False#include <unordered_set>#include <vector>using namespace std;
class Solution {public: bool containsDuplicate(vector<int>& nums) { unordered_set<int> seen; for (int num : nums) { if (seen.count(num)) return true; seen.insert(num); } return false; }};import java.util.HashSet;import java.util.Set;
class Solution { public boolean containsDuplicate(int[] nums) { Set<Integer> seen = new HashSet<>(); for (int num : nums) { if (seen.contains(num)) return true; seen.add(num); } return false; }}function containsDuplicate(nums) { const seen = new Set(); for (const num of nums) { if (seen.has(num)) return true; seen.add(num); } return false;}use std::collections::HashSet;
impl Solution { pub fn contains_duplicate(nums: Vec<i32>) -> bool { let mut seen = HashSet::new(); for num in nums { if !seen.insert(num) { return true; } } false }}func containsDuplicate(nums []int) bool { seen := map[int]bool{} for _, num := range nums { if seen[num] { return true } seen[num] = true } return false}Approach 2: Sorting
Section titled “Approach 2: Sorting”Sort the array first. After sorting, any duplicate values must be adjacent. A single pass then detects any pair of equal neighbours.
Step-by-step Example
Section titled “Step-by-step Example”Input: [3, 1, 3, 2]
After sorting: [1, 3, 3, 2] → wait: [1, 2, 3, 3]
| i | nums[i] | nums[i-1] | Equal? |
|---|---|---|---|
| 1 | 2 | 1 | No |
| 2 | 3 | 2 | No |
| 3 | 3 | 3 | Yes → return true |
Pseudocode
Section titled “Pseudocode”function containsDuplicate(nums): sort(nums) for i from 1 to len(nums) - 1: if nums[i] == nums[i - 1]: return true return falseSolution Code
Section titled “Solution Code”from typing import List
def contains_duplicate(nums: List[int]) -> bool: nums.sort() for i in range(1, len(nums)): if nums[i] == nums[i - 1]: return True return False
print(contains_duplicate([1, 2, 3, 1])) # Trueprint(contains_duplicate([1, 2, 3, 4])) # False#include <algorithm>#include <vector>using namespace std;
class Solution {public: bool containsDuplicate(vector<int>& nums) { sort(nums.begin(), nums.end()); for (int i = 1; i < (int)nums.size(); i++) { if (nums[i] == nums[i - 1]) return true; } return false; }};import java.util.Arrays;
class Solution { public boolean containsDuplicate(int[] nums) { Arrays.sort(nums); for (int i = 1; i < nums.length; i++) { if (nums[i] == nums[i - 1]) return true; } return false; }}function containsDuplicate(nums) { nums.sort((a, b) => a - b); for (let i = 1; i < nums.length; i++) { if (nums[i] === nums[i - 1]) return true; } return false;}impl Solution { pub fn contains_duplicate(mut nums: Vec<i32>) -> bool { nums.sort_unstable(); nums.windows(2).any(|w| w[0] == w[1]) }}package golangimport "sort"
func containsDuplicate(nums []int) bool { sort.Ints(nums) for i := 1; i < len(nums); i++ { if nums[i] == nums[i-1] { return true } }
} return falseApproach 3: Space-Optimized Variant
Section titled “Approach 3: Space-Optimized Variant”A third approach demonstrating an alternative technique for solving this problem. This implementation optimizes either time or space complexity compared to the previous approaches.
Pseudocode
Section titled “Pseudocode”function approach3(): // Implementation approach goes hereSolution Code
Section titled “Solution Code”"""Solution for Contains Duplicate"""
def solve(): """Implementation for approach 3 of Contains Duplicate""" pass
if __name__ == "__main__": print("Solution ready")#include <bits/stdc++.h>using namespace std;
// Solution for Contains Duplicate// Approach 3: Implementation
int main() {{ // Main implementation goes here return 0;}}/** * Solution for Contains Duplicate * Approach 3 */public class ContainsDuplicateSpaceOptimized {{
public static void main(String[] args) {{ // Implementation goes here }}}}/** * Solution for Contains Duplicate * Approach 3 */
function solve() {{ // Implementation goes here}}
module.exports = solve;/// Solution for Contains Duplicate/// Approach 3
fn main() {{ println!("Solution implementation");}}package main
import "fmt"
// Solution for Contains Duplicate// Approach 3
func main() {{ fmt.Println("Solution implementation")}}