You are given a list of whole numbers, nums. Decide whether some value shows up in it more than once.
Return true if at least one value repeats, and false if all the numbers are different from each other.
Example 1
Input: nums = [7, 3, 9, 3] Output: true Why: 3 sits at positions 1 and 3
2 more examples and the constraints
Example 2
Input: nums = [5, 8, 2] Output: false Why: no two numbers are equal
Example 3
Input: nums = [-4, 0, -4, 0, 6] Output: true Why: both -4 and 0 appear twice
Constraints
- 1 ≤ length of nums ≤ 100,000
- Each number is between −1,000,000,000 and 1,000,000,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Brute forceO(n²)
- Sort, then check neighboursO(n log n)
- Hash set, one passO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100,000 numbers | Verdict |
|---|---|---|---|
| Brute force | O(n²) | Mention it, then move on | |
| Sort, then check neighbours | O(n log n) | Passes; no extra memory | |
| Hash set, one pass | O(n) | Best; stops at the first repeat |
n = how many numbers are in the list.
Edge cases to test
- One number. [5] has nothing to repeat, so the answer is
false. - Repeat at the very end. The match may only appear on the last number read.
- Negative values. [-4, 0, -4] repeats −4; signs need no special care.
- Values at the limits. −1,000,000,000 and 1,000,000,000 are different numbers, not a repeat.
Common mistakes
- Adding the number to the set before checking it, so every number looks like a repeat.
- Comparing only neighbours without sorting first.
- Counting every value when a single repeat already answers the question.
How to talk through it
- 1Clarify. Can the list be empty? May I change the input array, for example by sorting it?
- 2Give the brute force. Check every pair; say it is O(n²) and too slow for 100,000 numbers.
- 3Offer the sort. Sorting puts equal values next to each other, so one pass over neighbours works in O(n log n).
- 4Code the hash set. Check membership first, then add. Point out the early return.
- 5Test out loud. Run the single-number case and a repeat on the last position before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?