Contains Duplicate
The drill: Decide whether any value appears more than once in the array — a single repeated value anywhere is enough to say yes.
A list of integers arrives, and the only question is whether any single value shows up more than once anywhere inside it.
There's no need to say which value repeats or how many times — a plain yes-or-no answer is all that's asked for, based purely on whether at least one collision exists.
Order in the array carries no meaning here; only presence and repetition matter. A completely unique list, even one arranged in a wildly scrambled order, answers no.
- arrays can run from empty up to a good many thousand elements
- values may repeat any number of times, or not at all
- values can be negative, zero, or positive
- the answer is a single boolean, true the moment any repeat exists
HINT 1 THE NUDGE
The quadratic way compares every pair. But “is there a repeat” never needs pairs — it needs memory of what you have already walked past.
HINT 2 THE STRUCTURE
A set answers “have I seen this?” in O(1). What is the earliest moment you can answer yes?
HINT 3 ONE STEP FROM THE ANSWER
Insert as you scan: if the value is already in the set, you are done. Finishing the scan clean means no duplicates.
The seen set starts empty. Watch for the moment a value repeats one already stored.
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
seen = set()
for v in nums:
if v in seen:
return True
seen.add(v)
return Falseclass Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
if nums[i] == nums[j]:
return True
return Falseclass Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> seen = new HashSet<>();
for (int v : nums) {
if (!seen.add(v)) {
return true;
}
}
return false;
}
}class Solution {
public boolean containsDuplicate(int[] nums) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] == nums[j]) {
return true;
}
}
}
return false;
}
}✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED