Skip to content

Commit a6321cf

Browse files
Add solution for longest substring without repeating characters
This commit introduces an implementation for finding the length of the longest substring without repeating characters using the sliding window technique. Includes a unit test to verify correctness with example test cases.
1 parent af4fec2 commit a6321cf

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# https://neetcode.io/problems/longest-substring-without-duplicates
2+
3+
import unittest
4+
5+
def length_of_longest_substring(s: str) -> int:
6+
seen = set()
7+
left = 0
8+
result = 0
9+
10+
for right, char in enumerate(s):
11+
# Continuously remove leftmost characters from seen and move
12+
# the left pointer forward whenever a duplicate is encountered
13+
14+
while char in seen:
15+
seen.remove(s[left]) # Remove the leftmost character
16+
left += 1 # Shrink the window until the duplicate is removed
17+
continue
18+
19+
seen.add(char)
20+
21+
# Update the result with the current size of the window
22+
result = max(result, right - left + 1)
23+
24+
return result
25+
26+
class Test(unittest.TestCase):
27+
def test_length_of_longest_substring(self):
28+
self.assertEqual(length_of_longest_substring("zxyzxyz"), 3)
29+
self.assertEqual(length_of_longest_substring("xxxx"), 1)

0 commit comments

Comments
 (0)