Skip to content

Commit ef65d61

Browse files
committed
add solution: longest-substring-without-repeating-characters
1 parent 2cefe92 commit ef65d61

File tree

1 file changed

+35
-0
lines changed
  • longest-substring-without-repeating-characters

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
'''
2+
# 3. Longest Substring Without Repeating Characters
3+
4+
use a set to store the characters in the current substring.
5+
6+
7+
## Time and Space Complexity
8+
9+
```
10+
TC: O(n)
11+
SC: O(n)
12+
```
13+
14+
#### TC is O(n):
15+
- iterating with end pointer through the string once. = O(n)
16+
- inner while loop runs at most once for each character in the string. = Amortized O(1)
17+
18+
#### SC is O(n):
19+
- using a set to store the characters in the current substring. = O(n)
20+
21+
'''
22+
class Solution:
23+
def lengthOfLongestSubstring(self, s: str) -> int:
24+
max_count = 0
25+
start = 0
26+
substrings = set() # SC: O(n)
27+
28+
for end in range(len(s)): # TC: O(n)
29+
while s[end] in substrings: # TC: Amortized O(1)
30+
substrings.remove(s[start])
31+
start += 1
32+
substrings.add(s[end])
33+
max_count = max(max_count, end - start + 1)
34+
35+
return max_count

0 commit comments

Comments
 (0)