Contains Duplicate
EasyA set remembers everything you've seen
Remember every number you've seen; if one shows up again, you've found a repeat.
The idea
Keep a set of seen values. The first time you try to add a value that's already there, you've found a duplicate.
1
2
3
1
0
1
2
3
Step 1 of 4. Brute force: compare every pair to look for a repeat. Values: 1, 2, 3, 1.
1/4
Brute force
timeO(n²)spaceO(1)
Compare every pair.
1// compare every pair2for (let i = 0; i < n; i++)3 for (let j = i + 1; j < n; j++)4 if (nums[i] === nums[j]) return true;5return false;Input
- array
- [1, 2, 3, 1]
Memory
- i
- —
- j
- —
- pairs tried
- —
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Examples
Example 1
- Input:
- nums = [1, 2, 3, 1]
- Output:
- true
- Explanation:
- 1 appears twice.
Example 2
- Input:
- nums = [1, 2, 3, 4]
- Output:
- false
- Explanation:
- Every value is unique.
Example 3
- Input:
- nums = [1, 1, 1, 1]
- Output:
- true
- Explanation:
- Lots of repeats.
Practice this problem:LeetCode(opens in a new tab)Search GeeksforGeeks(opens in a new tab)
Finished the walkthrough? Add it to your streak.