Skip to content
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

Create sliding_window.py #11581

Open
wants to merge 13 commits into
base: master
Choose a base branch
from
Open
48 changes: 48 additions & 0 deletions greedy_methods/sliding_window.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
def sliding_window(s: str) -> int:
OmMahajan29 marked this conversation as resolved.
Show resolved Hide resolved
"""
This function takes a string and returns the length of the longest substring
without repeating characters using the sliding window algorithm.

Args:
s: A string input.

Returns:
max_len: Length of the longest substring without repeating characters.

Examples:
>>> sliding_window("abcabcbb")
3
>>> sliding_window("bbbbb")
1
>>> sliding_window("pwwkew")
3
>>> sliding_window("")
0
>>> sliding_window("abcdefg")
7
>>> sliding_window("abccba")
3
Comment on lines +18 to +30
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you make it more enhanced ?

Copy link
Author

@OmMahajan29 OmMahajan29 Sep 25, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Enhanced in what way? Any specifics?

"""
char_index_map = {}
left = 0
max_len = 0

# Traverse the string with a right pointer
for right, char in enumerate(s):
if char in char_index_map and char_index_map[char] >= left:
# Move the left pointer to avoid repeating characters
left = char_index_map[char] + 1

# Update the latest index of the character
char_index_map[char] = right

# Calculate the current length of the window
max_len = max(max_len, right - left + 1)

return max_len


if __name__ == "__main__":
import doctest

doctest.testmod()