Skip to content

Commit 1117ffe

Browse files
Optimize longest_non_repeat.py (#914)
Added window sliding approach to find longest non repeating sub string
1 parent a336ee8 commit 1117ffe

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

algorithms/arrays/longest_non_repeat.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,4 +88,22 @@ def get_longest_non_repeat_v2(string):
8888
max_len = index - start + 1
8989
sub_string = string[start: index + 1]
9090
used_char[char] = index
91-
return max_len, sub_string
91+
return max_len, sub_string
92+
93+
def get_longest_non_repeat_v3(string):
94+
"""
95+
Find the length of the longest substring
96+
without repeating characters.
97+
Uses window sliding approach.
98+
Return max_len and the substring as a tuple
99+
"""
100+
longest_substring = ''
101+
seen = set()
102+
start_idx = 0
103+
for i in range(len(string)):
104+
while string[i] in seen:
105+
seen.remove(string[start_idx])
106+
start_idx += 1
107+
seen.add(string[i])
108+
longest_substring = max(longest_substring, string[start_idx: i+1], key=len)
109+
return len(longest_substring), longest_substring

0 commit comments

Comments
 (0)