Skip to content

Commit 80bec23

Browse files
Merge pull request #18 from codewithme-py/feat/contains-duplicate-iii-0220
problem solution & test 0220
2 parents ab04f6b + 55ceb35 commit 80bec23

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Solution:
2+
def containsNearbyAlmostDuplicate(
3+
self, nums: list[int], indexDiff: int, valueDiff: int
4+
) -> bool:
5+
"""
6+
Look for two different indices i and j, where:
7+
1. |i - j| <= indexDiff (indices are close)
8+
2. |nums[i] - nums[j]| <= valueDiff (values are close)
9+
Args:
10+
nums (list[int]): Input array.
11+
indexDiff (int): Maximum distance between indices.
12+
valueDiff (int): Maximum distance between values.
13+
Returns:
14+
bool: True, if a suitable pair of indices is found, otherwise False.
15+
Time Complexity:
16+
O(n) — each element is processed once,
17+
checking 3 buckets = O(1).
18+
Space Complexity:
19+
O(min(n, indexDiff)) — we store at most indexDiff buckets.
20+
"""
21+
if valueDiff < 0 or indexDiff <= 0:
22+
return False
23+
buckets = {}
24+
bucket_size = valueDiff + 1
25+
for i, num in enumerate(nums):
26+
bucket_id = num // bucket_size
27+
if bucket_id in buckets:
28+
return True
29+
if (bucket_id - 1 in buckets
30+
and abs(num - buckets[bucket_id - 1]) <= valueDiff):
31+
return True
32+
if (bucket_id + 1 in buckets
33+
and abs(num - buckets[bucket_id + 1]) <= valueDiff):
34+
return True
35+
buckets[bucket_id] = num
36+
if i >= indexDiff:
37+
del buckets[nums[i - indexDiff] // bucket_size]
38+
return False
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import pytest
2+
3+
from solutions.contains_duplicate_iii_0220 import Solution
4+
5+
6+
@pytest.mark.parametrize(
7+
'nums, index_diff, value_diff, expected', [
8+
([1,2,3,1], 3, 0, True),
9+
([1,5,9,1,5,9], 2, 3, False),
10+
]
11+
)
12+
def test_solution(nums, index_diff, value_diff, expected) -> None:
13+
sol = Solution()
14+
assert sol.containsNearbyAlmostDuplicate(nums, index_diff, value_diff) == expected

0 commit comments

Comments
 (0)