Skip to content

Commit 9d3db91

Browse files
committed
D. J.:
- Add the leetcode problem and solution for 219 Contains Duplicates II
1 parent 9d764fd commit 9d3db91

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ This repository contains awesome LeetCode problems and solutions written in Pyth
1919
- [189 Rotate Array](https://leetcode.com/problems/rotate-array/description/)
2020
- [202 Happy Number](https://leetcode.com/problems/happy-number/description/)
2121
- [205 Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/description/)
22+
- [219 Contains Duplicates II](https://leetcode.com/problems/contains-duplicate-ii/description/)
2223
- [242 Valid Anagram](https://leetcode.com/problems/valid-anagram/description/)
2324
- [290 Word Pattern](https://leetcode.com/problems/word-pattern/description/)
2425
- [383 Ransom Note](https://leetcode.com/problems/ransom-note/description/)
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
6+
"""
7+
Given an integer array nums and an integer k, return true if there are
8+
two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.
9+
"""
10+
11+
sliding_window = set()
12+
left = 0
13+
for right in range(len(nums)):
14+
if right - left > k:
15+
sliding_window.remove(nums[left])
16+
left += 1
17+
if nums[right] in sliding_window:
18+
return True
19+
sliding_window.add(nums[right])
20+
return False
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
from typing import List
2+
3+
import pytest
4+
5+
from awesome_python_leetcode._219_contains_duplicate_II import Solution
6+
7+
8+
@pytest.mark.parametrize(
9+
argnames=["nums", "k", "expected"],
10+
argvalues=[
11+
([1, 2, 3, 1], 3, True),
12+
([1, 0, 1, 1], 1, True),
13+
([1, 2, 3, 1, 2, 3], 2, False),
14+
],
15+
)
16+
def test_func(nums: List[int], k: int, expected: bool):
17+
contains_nearby_duplicate = Solution().containsNearbyDuplicate(nums, k)
18+
assert contains_nearby_duplicate == expected

0 commit comments

Comments
 (0)