File tree Expand file tree Collapse file tree 1 file changed +30
-2
lines changed
longest-substring-without-repeating-characters Expand file tree Collapse file tree 1 file changed +30
-2
lines changed Original file line number Diff line number Diff line change 6
6
7
7
## Time and Space Complexity
8
8
9
+ ### Solution 1: using set
10
+
9
11
```
10
12
TC: O(n)
11
13
SC: O(n)
12
14
```
13
15
14
- #### TC is O(n):
16
+ #### TC is O(n):
15
17
- iterating with end pointer through the string once. = O(n)
16
18
- inner while loop runs at most once for each character in the string. = Amortized O(1)
17
19
18
20
#### SC is O(n):
19
21
- using a set to store the characters in the current substring. = O(n)
20
22
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)
21
36
'''
22
37
class Solution :
23
- def lengthOfLongestSubstring (self , s : str ) -> int :
38
+ def lengthOfLongestSubstringWithSet (self , s : str ) -> int :
24
39
max_count = 0
25
40
start = 0
26
41
substrings = set () # SC: O(n)
@@ -33,3 +48,16 @@ def lengthOfLongestSubstring(self, s: str) -> int:
33
48
max_count = max (max_count , end - start + 1 )
34
49
35
50
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
You can’t perform that action at this time.
0 commit comments