Skip to content

Data structure/sliding window examples #11520

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions data_structures/sliding_window/longest_substring_two_distinct.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
def length_of_longest_substring_two_distinct(s):

Check failure on line 1 in data_structures/sliding_window/longest_substring_two_distinct.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (INP001)

data_structures/sliding_window/longest_substring_two_distinct.py:1:1: INP001 File `data_structures/sliding_window/longest_substring_two_distinct.py` is part of an implicit namespace package. Add an `__init__.py`.
"""
Finds the length of the longest substring with at most two distinct characters.[https://www.geeksforgeeks.org/window-sliding-technique/]


Args:
s (str): The input string.

Returns:
int: The length of the longest substring with at most two distinct characters.

Examples:
>>> length_of_longest_substring_two_distinct("eceba")
3
>>> length_of_longest_substring_two_distinct("ccaabbb")
5
>>> length_of_longest_substring_two_distinct("abcabcabc")
2
>>> length_of_longest_substring_two_distinct("")
0
"""
n = len(s)
if n == 0:
return 0

Check failure on line 25 in data_structures/sliding_window/longest_substring_two_distinct.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

data_structures/sliding_window/longest_substring_two_distinct.py:25:1: W293 Blank line contains whitespace
# Dictionary to store the last occurrence of each character
char_map = {}
left = 0
max_length = 0

Check failure on line 30 in data_structures/sliding_window/longest_substring_two_distinct.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

data_structures/sliding_window/longest_substring_two_distinct.py:30:1: W293 Blank line contains whitespace
# Sliding window approach
for right in range(n):
char_map[s[right]] = right

Check failure on line 34 in data_structures/sliding_window/longest_substring_two_distinct.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

data_structures/sliding_window/longest_substring_two_distinct.py:34:1: W293 Blank line contains whitespace
# If we have more than two distinct characters
if len(char_map) > 2:
# Remove the leftmost character
del_idx = min(char_map.values())
del char_map[s[del_idx]]
left = del_idx + 1

Check failure on line 41 in data_structures/sliding_window/longest_substring_two_distinct.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

data_structures/sliding_window/longest_substring_two_distinct.py:41:1: W293 Blank line contains whitespace
max_length = max(max_length, right - left + 1)

Check failure on line 43 in data_structures/sliding_window/longest_substring_two_distinct.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

data_structures/sliding_window/longest_substring_two_distinct.py:43:1: W293 Blank line contains whitespace
return max_length

if __name__ == "__main__":
import doctest
doctest.testmod()
40 changes: 40 additions & 0 deletions data_structures/sliding_window/max_sum_subarray.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
def max_sum_subarray(arr, k):

Check failure on line 1 in data_structures/sliding_window/max_sum_subarray.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (INP001)

data_structures/sliding_window/max_sum_subarray.py:1:1: INP001 File `data_structures/sliding_window/max_sum_subarray.py` is part of an implicit namespace package. Add an `__init__.py`.
"""
Finds the maximum sum of a subarray of length k within the given array.[https://www.geeksforgeeks.org/window-sliding-technique/]

Args:
arr (list): The input array.
k (int): The length of the subarray.

Returns:
int: The maximum sum of a subarray of length k.

Examples:
>>> max_sum_subarray([1, 2, 3, 4, 5], 2)
9
>>> max_sum_subarray([1, 2, 3, 4, 5], 3)
12
>>> max_sum_subarray([1, 2, 3, 4, 5], 6)
Invalid input: k is larger than the array size
>>> max_sum_subarray([], 1)
Invalid input: k is larger than the array size
"""
n = len(arr)
if n < k or k <= 0:
print("Invalid input: k is larger than the array size or non-positive")
return None

Check failure on line 26 in data_structures/sliding_window/max_sum_subarray.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

data_structures/sliding_window/max_sum_subarray.py:26:1: W293 Blank line contains whitespace
# Calculate the sum of the first window of size k
window_sum = sum(arr[:k])
max_sum = window_sum

Check failure on line 30 in data_structures/sliding_window/max_sum_subarray.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

data_structures/sliding_window/max_sum_subarray.py:30:1: W293 Blank line contains whitespace
# Slide the window from start to end of the array
for i in range(n - k):
window_sum = window_sum - arr[i] + arr[i + k]
max_sum = max(max_sum, window_sum)

return max_sum

if __name__ == "__main__":
import doctest
doctest.testmod()
40 changes: 40 additions & 0 deletions data_structures/sliding_window/min_subarray_len.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
def min_subarray_len(target, nums):
"""
Finds the minimal length of a contiguous subarray of which the sum is at least the target.[https://www.geeksforgeeks.org/window-sliding-technique/]


Args:
target (int): The target sum.
nums (list): The list of positive integers.

Returns:
int: The minimal length of a contiguous subarray with a sum at least equal to the target, or 0 if no such subarray exists.

Examples:
>>> min_subarray_len(7, [2,3,1,2,4,3])
2
>>> min_subarray_len(4, [1,4,4])
1
>>> min_subarray_len(11, [1,1,1,1,1,1,1,1])
0
>>> min_subarray_len(15, [5,1,3,5,10,7,4,9,2,8])
2
"""
n = len(nums)
left = 0
current_sum = 0
min_length = float('inf')

for right in range(n):
current_sum += nums[right]

while current_sum >= target:
min_length = min(min_length, right - left + 1)
current_sum -= nums[left]
left += 1

return min_length if min_length != float('inf') else 0

if __name__ == "__main__":
import doctest
doctest.testmod()
Loading