Example 1
ready- Input
nums = [ 14, 3, 8, 14 ]- Expected
true- Why
- 14 appears at both ends
A repeated order ID can turn one shipment into two. Your first job is to catch the repeat.
A duplicate is a value that appears in more than one position. Given an integer array
nums, return true when it contains a duplicate; return false when every value appears
exactly once.
A few ground rules:
1 <= nums.length <= 100_000-1_000_000_000 <= nums[i] <= 1_000_000_000Hints
Pick one position and compare it with every later position. That works, but how many comparisons does an array of 100,000 distinct values force you to make?
A hash set is a collection that stores unique values and supports fast membership checks. While scanning, it can answer: "have I seen this value before?"
For each value, check the set first. If the value is present, return true; otherwise,
add it and continue. Reaching the end means every value was new.
Could your approach detect a duplicate while the numbers arrive as a stream, without storing the entire input array?
Visible cases
nums = [
14,
3,
8,
14
]truenums = [
7,
-2,
9,
4
]falsenums = [
5,
5,
8,
10
]trueInterview signal
Compare each value with every value to its right. A matching pair proves a duplicate exists; if every pair differs, the array is distinct.
def contains_duplicate(nums: list[int]) -> bool:
for i in range(len(nums) - 1):
for j in range(i + 1, len(nums)):
if nums[i] == nums[j]:
return True
return FalseTime O(n²) in the all-distinct case, because you inspect every pair. Space O(1). At 100,000 values, that pair count is the deal-breaker.
A hash set is a collection of unique values with O(1) expected membership checks.
Walk through nums once and keep the values you've passed. Seeing a value already in
the set gives you the answer immediately.
def contains_duplicate(nums: list[int]) -> bool:
seen: set[int] = set()
for value in nums:
if value in seen:
return True
seen.add(value)
return FalseChecking before adding matters: every value would appear in the set after its own insert. The check asks whether an earlier position held the same value.
Time O(n) expected, with one lookup and at most one insert per value. Space O(n) when every value is distinct and the set must remember all of them.
Ready to run.
3 cases are queued.
Visible testcase
Case 1
Expected
true