-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestsubstring_withoutrepeatingcharacters_Day18.py
More file actions
58 lines (43 loc) · 1.27 KB
/
Copy pathLongestsubstring_withoutrepeatingcharacters_Day18.py
File metadata and controls
58 lines (43 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#Brute Force Approach
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
def all_unique(sub: str) -> bool:
return len(set(sub)) == len(sub)
max_len = 0
n = len(s)
for i in range(n):
for j in range(i+1, n+1):
if all_unique(s[i:j]):
max_len = max(max_len, j - i)
return max_len
# TC - O(N³)
# SC - O(N)
#Better Approach
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
char_set = set()
left = 0
max_len = 0
for right in range(len(s)):
while s[right] in char_set:
char_set.remove(s[left])
left += 1
char_set.add(s[right])
max_len = max(max_len, right - left + 1)
return max_len
# TC - O(2N)
# SC - O(N)
#Optimal Approach
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
char_map = {}
left = 0
max_len = 0
for right in range(len(s)):
if s[right] in char_map and char_map[s[right]] >= left:
left = char_map[s[right]] + 1
char_map[s[right]] = right
max_len = max(max_len, right - left + 1)
return max_len
# TC - O(N)
# SC - O(N)