|
| 1 | +# 3. Longest Substring Without Repeating Characters |
| 2 | + |
| 3 | +## Sliding Window Solution |
| 4 | +- Run-time: O(N) or 2N |
| 5 | +- Space: O(N) |
| 6 | +- N = Number of characters in string |
| 7 | + |
| 8 | +Using a sliding window and a set, we can identify when we need to move the left side of the sliding window when a duplicate character is found as well as when to stop. |
| 9 | + |
| 10 | +This solution is actually a two pass solution, due to the fact we have to remove elements on the left side from the set, hence, visiting each element twice. |
| 11 | + |
| 12 | +``` |
| 13 | +class Solution: |
| 14 | + def lengthOfLongestSubstring(self, s: str) -> int: |
| 15 | + seen = set() |
| 16 | + left_idx = longest_substr = 0 |
| 17 | + for idx, ch in enumerate(s): |
| 18 | + while ch in seen and left_idx <= idx: |
| 19 | + seen.remove(s[left_idx]) |
| 20 | + left_idx += 1 |
| 21 | + seen.add(ch) |
| 22 | + longest_substr = max(longest_substr, len(seen)) |
| 23 | + return longest_substr |
| 24 | +``` |
| 25 | + |
| 26 | +## One Pass Solution |
| 27 | +- Run-time: O(N) |
| 28 | +- Space: O(N) |
| 29 | +- N = Number of characters in string |
| 30 | + |
| 31 | +To perform a one pass solution, we can use a dictionary where the key is the character and the value is its index. |
| 32 | +Similar to the set, we can use the dictionary to check if we have a duplicate in our sliding window. |
| 33 | +If that is true, we can immediately move the left side to the previous duplicated character's index + 1. |
| 34 | + |
| 35 | +``` |
| 36 | +class Solution: |
| 37 | + def lengthOfLongestSubstring(self, s: str) -> int: |
| 38 | + seen = dict() |
| 39 | + left_idx = longest_substr = 0 |
| 40 | + for idx, ch in enumerate(s): |
| 41 | + if ch in seen: |
| 42 | + left_idx = seen[ch] + 1 |
| 43 | + seen[ch] = idx |
| 44 | + longest_substr = max(longest_substr, idx - left_idx + 1) |
| 45 | + return longest_substr |
| 46 | +``` |
0 commit comments