Skip to content

Commit e2941b1

Browse files
committed
update solution: longest-substring-without-repeating-characters
1 parent ef65d61 commit e2941b1

File tree

1 file changed

+30
-2
lines changed
  • longest-substring-without-repeating-characters

1 file changed

+30
-2
lines changed

longest-substring-without-repeating-characters/dusunax.py

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,21 +6,36 @@
66
77
## Time and Space Complexity
88
9+
### Solution 1: using set
10+
911
```
1012
TC: O(n)
1113
SC: O(n)
1214
```
1315
14-
#### TC is O(n):
16+
#### TC is O(n):
1517
- iterating with end pointer through the string once. = O(n)
1618
- inner while loop runs at most once for each character in the string. = Amortized O(1)
1719
1820
#### SC is O(n):
1921
- using a set to store the characters in the current substring. = O(n)
2022
23+
### Solution 2: using ASCII array
24+
25+
```
26+
TC: O(n)
27+
SC: O(128)
28+
```
29+
30+
#### TC is O(n):
31+
- iterating with end pointer through the string once. = O(n)
32+
- checking if the character is in the current substring.
33+
34+
#### SC is O(1):
35+
- using an array to store the characters in the current substring. = constant space O(128)
2136
'''
2237
class Solution:
23-
def lengthOfLongestSubstring(self, s: str) -> int:
38+
def lengthOfLongestSubstringWithSet(self, s: str) -> int:
2439
max_count = 0
2540
start = 0
2641
substrings = set() # SC: O(n)
@@ -33,3 +48,16 @@ def lengthOfLongestSubstring(self, s: str) -> int:
3348
max_count = max(max_count, end - start + 1)
3449

3550
return max_count
51+
52+
def lengthOfLongestSubstring(self, s: str) -> int:
53+
max_count = 0
54+
start = 0
55+
char_index = [-1] * 128 # SC: O(128)
56+
57+
for end in range(len(s)): # TC: O(n)
58+
if char_index[ord(s[end])] >= start:
59+
start = char_index[ord(s[end])] + 1
60+
char_index[ord(s[end])] = end
61+
max_count = max(max_count, end - start + 1)
62+
63+
return max_count

0 commit comments

Comments
 (0)