diff --git a/0003_longest-substring-without-repeating-characters/README.md b/0003_longest-substring-without-repeating-characters/README.md new file mode 100644 index 0000000..f1a1c79 --- /dev/null +++ b/0003_longest-substring-without-repeating-characters/README.md @@ -0,0 +1,30 @@ +Given a string `s`, find the length of the **longest substring** without repeating characters. + +**Example 1:** + + Input: s = "abcabcbb" + Output: 3 + Explanation: The answer is "abc", with the length of 3. + + +**Example 2:** + + Input: s = "bbbbb" + Output: 1 + Explanation: The answer is "b", with the length of 1. + + +**Example 3:** + + Input: s = "pwwkew" + Output: 3 + Explanation: The answer is "wke", with the length of 3. + Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. + + +**Constraints:** + +* `0 <= s.length <= 5 * 104` +* `s` consists of English letters, digits, symbols and spaces. + +https://leetcode.com/problems/longest-substring-without-repeating-characters \ No newline at end of file diff --git a/0003_longest-substring-without-repeating-characters/python3/solution.py b/0003_longest-substring-without-repeating-characters/python3/solution.py new file mode 100644 index 0000000..0cc487c --- /dev/null +++ b/0003_longest-substring-without-repeating-characters/python3/solution.py @@ -0,0 +1,29 @@ +# Time: O(N) +# Space: O(N) +class Solution: + def lengthOfLongestSubstring(self, s: str) -> int: + ''' + Sliding-window approach + ''' + + # Keep a track of unique chars we've seen so far in the substring + # we are looking at + seen = set() + start, end = 0, 0 + maxl = 0 + + while start <= end < len(s): + # Our current substring is denoted by their bounds [start, end] + # If we see a char in `end` which is already seen by us, we need + # to keep moving `start` until we are left with a new character + while s[end] in seen: + # Since `start` is moving up, we need to remove existing + # `start` char from the set if it exists + seen.remove(s[start]) + start += 1 + + seen.add(s[end]) + maxl = max(maxl, (end - start) + 1) + end += 1 + + return maxl