You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Page on leetcode: https://leetcode.com/problems/contains-duplicate/
4
+
5
+
## Problem Statement
6
+
7
+
Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.
8
+
9
+
### Constraints
10
+
11
+
- 1 <= nums.length <= 105
12
+
- -109 <= nums[i] <= 109
13
+
14
+
### Example
15
+
16
+
```
17
+
Input: nums = [1,2,3,1]
18
+
Output: true
19
+
```
20
+
21
+
```
22
+
Input: nums = [1,2,3,4]
23
+
Output: false
24
+
```
25
+
26
+
## Solution
27
+
28
+
Immediate thought is to use a hashmap and count the numbers as you iterate thru the array.
29
+
30
+
### Pseudocode
31
+
32
+
1. Create empty map
33
+
2. For loop thru array
34
+
3. If element exist in map return true
35
+
4. else add element to map with val 1
36
+
5. return false if it loops thru entire array
37
+
38
+
### Initial Solution
39
+
40
+
This solution has a time and space complexity of O(n).
41
+
42
+
```javascript
43
+
constcontainsDuplicate=function (nums) {
44
+
constmap= {};
45
+
46
+
for (let i =0; i <nums.length; i++) {
47
+
if (nums[i] in map) {
48
+
returntrue;
49
+
}
50
+
map[nums[i]] =1;
51
+
}
52
+
53
+
returnfalse;
54
+
};
55
+
```
56
+
57
+
### Alternative Solution
58
+
59
+
The below alternative has a time complexity O(nlogn) due to sorting, but has a space complexity of O(1). You can see explanations of different solutions here: https://www.youtube.com/watch?v=3OamzN90kPg
0 commit comments