Skip to content

Commit aed74dc

Browse files
committed
Sync LeetCode submission Runtime - 23 ms (51.93%), Memory - 26.2 MB (87.12%)
1 parent 70743c3 commit aed74dc

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <code>true</code> <em>if there are two <strong>distinct indices</strong> </em><code>i</code><em> and </em><code>j</code><em> in the array such that </em><code>nums[i] == nums[j]</code><em> and </em><code>abs(i - j) &lt;= k</code>.</p>
2+
3+
<p>&nbsp;</p>
4+
<p><strong class="example">Example 1:</strong></p>
5+
6+
<pre>
7+
<strong>Input:</strong> nums = [1,2,3,1], k = 3
8+
<strong>Output:</strong> true
9+
</pre>
10+
11+
<p><strong class="example">Example 2:</strong></p>
12+
13+
<pre>
14+
<strong>Input:</strong> nums = [1,0,1,1], k = 1
15+
<strong>Output:</strong> true
16+
</pre>
17+
18+
<p><strong class="example">Example 3:</strong></p>
19+
20+
<pre>
21+
<strong>Input:</strong> nums = [1,2,3,1,2,3], k = 2
22+
<strong>Output:</strong> false
23+
</pre>
24+
25+
<p>&nbsp;</p>
26+
<p><strong>Constraints:</strong></p>
27+
28+
<ul>
29+
<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
30+
<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>
31+
<li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li>
32+
</ul>
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# Approach 3: Hash Table
2+
3+
# Time: O(n)
4+
# Space: O(min(n, k))
5+
6+
class Solution:
7+
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
8+
hash_set = set()
9+
10+
for i in range(len(nums)):
11+
if nums[i] in hash_set:
12+
return True
13+
hash_set.add(nums[i])
14+
if len(hash_set) > k:
15+
hash_set.remove(nums[i - k])
16+
17+
return False
18+

0 commit comments

Comments
 (0)