Skip to content

Commit 23507f0

Browse files
authored
Create 2024-07-27-217-Contains-Duplicate.md
1 parent e55d991 commit 23507f0

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
---
2+
title: 217. Contains Duplicate
3+
author: nguyentp
4+
date: 2024-07-27
5+
tags: [leetcode]
6+
render_with_liquid: false
7+
---
8+
9+
# [Problem understanding](https://leetcode.com/problems/contains-duplicate/)
10+
11+
```
12+
Input: nums = [1,2,3,1]
13+
Output: true
14+
```
15+
16+
- 1 appears twice -> return True.
17+
- Base on the constraint, number could be negative or zero.
18+
19+
# Edge case
20+
21+
- empty list: False
22+
- single element: False
23+
- `[1, 1, 1, 1]` input: True
24+
25+
# Solution
26+
27+
1. 2 nested loop. Time N^2, Space N.
28+
2. Hash: `seen` hash table to check whether we have seen a number. Then go through each number, if we see it the first time, put it into the `seen` hash table. Otherwise, there is duplicate. Time: N, Space: N.
29+
30+
# Implement
31+
32+
```
33+
class Solution(object):
34+
def containsDuplicate(self, nums):
35+
"""
36+
:type nums: List[int]
37+
:rtype: bool
38+
"""
39+
if len(nums) <= 1:
40+
return False
41+
42+
seen = set()
43+
for n in nums:
44+
if n in seen:
45+
return True
46+
seen.add(n)
47+
return False
48+
```

0 commit comments

Comments
 (0)