Skip to content

Commit 2b1361c

Browse files
Merge pull request #17 from codewithme-py/feat/contains-duplicate-ii-0219
problem solution & test 0219
2 parents 9ca9bbe + 1d86664 commit 2b1361c

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Solution:
2+
def containsNearbyDuplicate(self, nums: list[int], k: int) -> bool:
3+
"""
4+
Function checks if there are duplicates in the array nums within k.
5+
set guarantees O(1) for addition and checking for existence.
6+
The size of set never exceeds k+1.
7+
Memory O(k)
8+
Time O(n)
9+
"""
10+
window_set = set()
11+
for i in range(len(nums)):
12+
if nums[i] in window_set:
13+
return True
14+
window_set.add(nums[i])
15+
if i >= k:
16+
window_set.remove(nums[i - k])
17+
return False
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import pytest
2+
3+
from solutions.contains_duplicate_ii_0219 import Solution
4+
5+
6+
@pytest.mark.parametrize('nums, k, expected', [
7+
([1,2,3,1], 3, True),
8+
([1,0,1,1], 1, True),
9+
([1,2,3,1,2,3], 2, False),
10+
([99,99], 2, True),
11+
([1,2,3,4,5,6,7,8,9,10], 3, False),
12+
])
13+
def test_solution(nums: list[int], k: int, expected: bool) -> None:
14+
sol = Solution()
15+
assert sol.containsNearbyDuplicate(nums, k) == expected

0 commit comments

Comments
 (0)