FresherFresher (0–1 yrs)CodingPythonAmazonApple
Contains Duplicate
Return true if any value appears at least twice in the array; otherwise false.
Answers use simple, clear English.
Audio N/ATime: O(n)Space: O(n)
Quick interview answer
Insert into a hash set while iterating. If an element is already present, return true. Sorting also works in O(n log n) with O(1) extra if mutation is allowed.
Detailed answer
Insert into a hash set while iterating. If an element is already present, return true. Sorting also works in O(n log n) with O(1) extra if mutation is allowed. Set approach is the default interview answer unless memory is constrained.
Full explanation
Set approach is the default interview answer unless memory is constrained.
Real example & use case
Deduplicating uploaded file hashes to reject repeat uploads in a media pipeline.
Pros & cons
Pros: expected O(n). Cons: O(n) memory; sorting trades time for space.
Code example
def contains_duplicate(nums: list[int]) -> bool:
seen: set[int] = set()
for x in nums:
if x in seen:
return True
seen.add(x)
return FalsePractice code · python (view only · no execution)
def contains_duplicate(nums: list[int]) -> bool:
seen: set[int] = set()
for x in nums:
if x in seen:
return True
seen.add(x)
return False#hashset#array