1. Hash Set (Early Termination Lookup)
OptimalIterate through elements while inserting them into a hash set. If an element already exists, immediately return true in O(1) average time.
We make at most a single pass over the array of N elements. Hash table lookups and insertions operate in O(1) average time.
In the worst case (when all elements are unique), the hash set stores all N numbers.
How It Works
The Core Mental Model: Instant Memory Lookback
When scanning an array sequentially, the naive human approach is to look ahead and compare every item with everything else. In software engineering, that forward scan leads to an unacceptable O(n²) nested loop.
Instead, we invert the question: "Have I seen this specific integer already?"
A Hash Set gives us average O(1) lookup and insertion:
- Initialize an empty hash set
seen. - For each number
numinnums:
- If
numis already present inseen, returntrueimmediately (early exit). - Otherwise, insert
numintoseen.
- If the loop completes without finding any repeated item, return
false.
Engineering Trade-Off: Time vs Memory
This approach trades auxiliary memory (up to N items stored in a hash bucket table) to achieve lightning-fast linear O(n) runtime. For interview discussions, mention that if memory is strictly constrained (e.g. microcontrollers or embedded memory limits), in-place sorting avoids the O(n) allocation.
Step-by-Step Dry Run
Check hash set. 1 is not in set. Add 1 to set.
set = {1}- +Optimal O(n) runtime
- +Early exit terminates as soon as first duplicate is spotted
- -Consumes O(n) auxiliary heap memory for hash table buckets
Reference Implementation
Complete implementation for Hash Set (Early Termination Lookup) in Python, JavaScript, Java, C++, and C.
def contains_duplicate(nums: list[int]) -> bool:seen = set()for num in nums:if num in seen:return Trueseen.add(num)return Falseif __name__ == "__main__":test1 = [1, 2, 3, 1]test2 = [1, 2, 3, 4]print("test1 contains duplicate:", contains_duplicate(test1))print("test2 contains duplicate:", contains_duplicate(test2))
function containsDuplicate(nums) {
const seen = new Set();
for (let i = 0; i < nums.length; i++) {
if (seen.has(nums[i])) {
return true;
}
seen.add(nums[i]);
}
return false;
}
// Example Execution
const test1 = [1, 2, 3, 1];
const test2 = [1, 2, 3, 4];
console.log("test1:", containsDuplicate(test1));
console.log("test2:", containsDuplicate(test2));import java.util.HashSet;
import java.util.Set;
public class Solution {
public static boolean containsDuplicate(int[] nums) {
Set<Integer> seen = new HashSet<>();
for (int num : nums) {
if (seen.contains(num)) {
return true;
}
seen.add(num);
}
return false;
}
public static void main(String[] args) {
int[] test1 = { 1, 2, 3, 1 };
int[] test2 = { 1, 2, 3, 4 };
System.out.println("test1: " + containsDuplicate(test1));
System.out.println("test2: " + containsDuplicate(test2));
}
}#include <iostream>
#include <vector>
#include <unordered_set>
bool containsDuplicate(const std::vector<int>& nums) {
std::unordered_set<int> seen;
for (int num : nums) {
if (seen.find(num) != seen.end()) {
return true;
}
seen.insert(num);
}
return false;
}
int main() {
std::vector<int> test1 = {1, 2, 3, 1};
std::vector<int> test2 = {1, 2, 3, 4};
std::cout << std::boolalpha;
std::cout << "test1: " << containsDuplicate(test1) << "\n";
std::cout << "test2: " << containsDuplicate(test2) << "\n";
return 0;
}#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
// Comparison function for qsort
int compareInts(const void* a, const void* b) {
int arg1 = *(const int*)a;
int arg2 = *(const int*)b;
if (arg1 < arg2) return -1;
if (arg1 > arg2) return 1;
return 0;
}
// In standard C without external hash maps, sorting provides O(n log n) with O(1) memory
bool containsDuplicate(int* nums, int numsSize) {
if (numsSize <= 1) return false;
qsort(nums, numsSize, sizeof(int), compareInts);
for (int i = 0; i < numsSize - 1; i++) {
if (nums[i] == nums[i + 1]) {
return true;
}
}
return false;
}
int main(void) {
int test1[] = {1, 2, 3, 1};
int test2[] = {1, 2, 3, 4};
printf("test1: %s\n", containsDuplicate(test1, 4) ? "true" : "false");
printf("test2: %s\n", containsDuplicate(test2, 4) ? "true" : "false");
return 0;
}