Intuition
The intuition behind the 3 solutions is to iteratively find the longest substring without repeating characters by maintaining a sliding window approach. We use two pointers (left
and right
) to represent the boundaries of the current substring. As we iterate through the string, we update the pointers and adjust the window to accommodate new unique characters and eliminate repeating characters.
Approach
- We use a set (
charSet
) to keep track of unique characters in the current substring. - We maintain two pointers,
left
andright
, to represent the boundaries of the current substring. - The
maxLength
variable keeps track of the length of the longest substring encountered so far. - We iterate through the string using the
right
pointer. - If the current character is not in the set (
charSet
), it means we have a new unique character. - We insert the character into the set and update the
maxLength
if necessary. - If the character is already present in the set, it indicates a repeating character within the current substring.
- In this case, we move the
left
pointer forward, removing characters from the set until the repeating character is no longer present. - We insert the current character into the set and continue the iteration.
- Finally, we return the
maxLength
as the length of the longest substring without repeating characters.
Complexity
- Time complexity:
- O(n)
- Space complexity:
- O(n)
Code
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
n = len(s)
maxLength = 0
charSet = set()
left = 0
for right in range(n):
if s[right] not in charSet:
charSet.add(s[right])
maxLength = max(maxLength, right - left + 1)
else:
while s[right] in charSet:
charSet.remove(s[left])
left += 1
charSet.add(s[right])
return maxLength