Skip to content

Commit 836ab89

Browse files
committed
feat(sliding_window): Add max sum subarray algorithm
Also updates DIRECTORY.md to include the new algorithm.
1 parent a71618f commit 836ab89

2 files changed

Lines changed: 64 additions & 0 deletions

File tree

DIRECTORY.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1258,6 +1258,9 @@
12581258
* [Tabu Search](searches/tabu_search.py)
12591259
* [Ternary Search](searches/ternary_search.py)
12601260

1261+
## Sliding Window
1262+
* [Maximum Sum Subarray](sliding_window/maximum_sum_subarray.py)
1263+
12611264
## Sorts
12621265
* [Bead Sort](sorts/bead_sort.py)
12631266
* [Binary Insertion Sort](sorts/binary_insertion_sort.py)
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# created by Mayank
2+
3+
"""
4+
Sliding Window Algorithm: Longest Substring Without Repeating Characters
5+
https://en.wikipedia.org/wiki/Sliding_window
6+
7+
This algorithm finds the length of the longest substring within a given string
8+
that does not contain any repeating characters. It uses a "sliding window"
9+
approach with two pointers to efficiently track the current substring.
10+
11+
Complexity: O(n) where n is the length of the string.
12+
13+
For doctests run following command:
14+
python3 -m doctest -v longest_substring_without_repeating_characters.py
15+
"""
16+
17+
18+
def longest_substring_without_repeating_characters(s: str) -> int:
19+
"""
20+
Finds the length of the longest substring without repeating characters.
21+
22+
:param s: The input string.
23+
:return: The length of the longest substring.
24+
25+
Examples:
26+
>>> longest_substring_without_repeating_characters("abcabcbb")
27+
3
28+
>>> longest_substring_without_repeating_characters("bbbbb")
29+
1
30+
>>> longest_substring_without_repeating_characters("pwwkew")
31+
3
32+
>>> longest_substring_without_repeating_characters("")
33+
0
34+
>>> longest_substring_without_repeating_characters("abcdef")
35+
6
36+
>>> longest_substring_without_repeating_characters("tmmzuxt")
37+
5
38+
"""
39+
char_set = set()
40+
left_pointer = 0
41+
max_length = 0
42+
43+
for right_pointer in range(len(s)):
44+
# If the character is already in the set, shrink the window from the left
45+
while s[right_pointer] in char_set:
46+
char_set.remove(s[left_pointer])
47+
left_pointer += 1
48+
49+
# Add the new character to the set (expanding the window)
50+
char_set.add(s[right_pointer])
51+
52+
# Update the maximum length found so far
53+
max_length = max(max_length, right_pointer - left_pointer + 1)
54+
55+
return max_length
56+
57+
58+
if __name__ == "__main__":
59+
import doctest
60+
61+
doctest.testmod()

0 commit comments

Comments
 (0)