Skip to content

Commit b29847c

Browse files
committed
Adding sliding window algorithm
I added three Python examples that demonstrate the sliding window technique.
1 parent 31c424f commit b29847c

File tree

3 files changed

+126
-0
lines changed

3 files changed

+126
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
def length_of_longest_substring_two_distinct(s):
2+
"""
3+
Finds the length of the longest substring with at most two distinct characters.
4+
5+
Args:
6+
s (str): The input string.
7+
8+
Returns:
9+
int: The length of the longest substring with at most two distinct characters.
10+
11+
Examples:
12+
>>> length_of_longest_substring_two_distinct("eceba")
13+
3
14+
>>> length_of_longest_substring_two_distinct("ccaabbb")
15+
5
16+
>>> length_of_longest_substring_two_distinct("abcabcabc")
17+
2
18+
>>> length_of_longest_substring_two_distinct("")
19+
0
20+
"""
21+
n = len(s)
22+
if n == 0:
23+
return 0
24+
25+
# Dictionary to store the last occurrence of each character
26+
char_map = {}
27+
left = 0
28+
max_length = 0
29+
30+
# Sliding window approach
31+
for right in range(n):
32+
char_map[s[right]] = right
33+
34+
# If we have more than two distinct characters
35+
if len(char_map) > 2:
36+
# Remove the leftmost character
37+
del_idx = min(char_map.values())
38+
del char_map[s[del_idx]]
39+
left = del_idx + 1
40+
41+
max_length = max(max_length, right - left + 1)
42+
43+
return max_length
44+
45+
if __name__ == "__main__":
46+
import doctest
47+
doctest.testmod()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
def max_sum_subarray(arr, k):
2+
"""
3+
Finds the maximum sum of a subarray of length k within the given array.
4+
5+
Args:
6+
arr (list): The input array.
7+
k (int): The length of the subarray.
8+
9+
Returns:
10+
int: The maximum sum of a subarray of length k.
11+
12+
Examples:
13+
>>> max_sum_subarray([1, 2, 3, 4, 5], 2)
14+
9
15+
>>> max_sum_subarray([1, 2, 3, 4, 5], 3)
16+
12
17+
>>> max_sum_subarray([1, 2, 3, 4, 5], 6)
18+
Invalid input: k is larger than the array size
19+
>>> max_sum_subarray([], 1)
20+
Invalid input: k is larger than the array size
21+
"""
22+
n = len(arr)
23+
if n < k or k <= 0:
24+
print("Invalid input: k is larger than the array size or non-positive")
25+
return None
26+
27+
# Calculate the sum of the first window of size k
28+
window_sum = sum(arr[:k])
29+
max_sum = window_sum
30+
31+
# Slide the window from start to end of the array
32+
for i in range(n - k):
33+
window_sum = window_sum - arr[i] + arr[i + k]
34+
max_sum = max(max_sum, window_sum)
35+
36+
return max_sum
37+
38+
if __name__ == "__main__":
39+
import doctest
40+
doctest.testmod()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
def min_subarray_len(target, nums):
2+
"""
3+
Finds the minimal length of a contiguous subarray of which the sum is at least the target.
4+
5+
Args:
6+
target (int): The target sum.
7+
nums (list): The list of positive integers.
8+
9+
Returns:
10+
int: The minimal length of a contiguous subarray with a sum at least equal to the target, or 0 if no such subarray exists.
11+
12+
Examples:
13+
>>> min_subarray_len(7, [2,3,1,2,4,3])
14+
2
15+
>>> min_subarray_len(4, [1,4,4])
16+
1
17+
>>> min_subarray_len(11, [1,1,1,1,1,1,1,1])
18+
0
19+
>>> min_subarray_len(15, [5,1,3,5,10,7,4,9,2,8])
20+
2
21+
"""
22+
n = len(nums)
23+
left = 0
24+
current_sum = 0
25+
min_length = float('inf')
26+
27+
for right in range(n):
28+
current_sum += nums[right]
29+
30+
while current_sum >= target:
31+
min_length = min(min_length, right - left + 1)
32+
current_sum -= nums[left]
33+
left += 1
34+
35+
return min_length if min_length != float('inf') else 0
36+
37+
if __name__ == "__main__":
38+
import doctest
39+
doctest.testmod()

0 commit comments

Comments
 (0)