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