Skip to content

Commit b497e84

Browse files
committed
refactor(arrays, subarrays): add doctests and edge cae
1 parent 7052e00 commit b497e84

2 files changed

Lines changed: 18 additions & 3 deletions

File tree

datastructures/arrays/subarrays_with_fixed_bounds/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ A subarray in nums is called a fixed-bound subarray if it satisfies the followin
1212
Constraints:
1313

1414
- 2 ≤ nums.length ≤ 10^3
15-
- 1 ≤ nums[i], minK, maxK ≤10^3
15+
- 1 ≤ nums[i], minK, maxK ≤ 10^3
1616

1717
## Examples
1818

datastructures/arrays/subarrays_with_fixed_bounds/__init__.py

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33

44
def count_subarrays(nums: List[int], min_k: int, max_k: int) -> int:
55
"""
6-
Counts the number of subarrays in the provided array which satisfies the following conditions:
6+
This counts the number of subarrays in the provided array which satisfies the following conditions:
7+
78
1. The smallest value in the subarray equals min_k.
89
2. The largest value in the subarray equals max_k.
910
@@ -14,7 +15,21 @@ def count_subarrays(nums: List[int], min_k: int, max_k: int) -> int:
1415
1516
Returns:
1617
int: The number of subarrays that satisfies the conditions.
18+
19+
Examples:
20+
>>> count_subarrays([2,1,4,3,2],2,3)
21+
1
22+
>>> count_subarrays([1,2,3,2,1],1,3)
23+
5
24+
>>> count_subarrays([4,4,4],4,4)
25+
6
26+
>>> count_subarrays([2,2,2],4,4)
27+
0
1728
"""
29+
# edge case to handle empty arrays or invalid bounds
30+
if not nums or min_k > max_k:
31+
return 0
32+
1833
last_min, last_max, last_invalid = -1, -1, -1
1934
count = 0
2035

@@ -28,4 +43,4 @@ def count_subarrays(nums: List[int], min_k: int, max_k: int) -> int:
2843

2944
count += max(0, min(last_min, last_max) - last_invalid)
3045

31-
return count
46+
return count

0 commit comments

Comments
 (0)