Longest Substring Without Repeating Characters
Look through a string for stretches of consecutive characters in which every character appears only once. In coddycode, the stretch ycode has five different characters, and no longer stretch avoids a repeat, so the answer is 5.
Checking every possible stretch works, but it is slow. A faster way keeps a window between two positions that never holds a repeat. Move the right edge one character at a time. When the new character is already inside the window, jump the left edge just past the place where that character was seen before. Remembering the last position of every character makes that jump instant, so the string is read only once.
Write a function named lengthOfLongestSubstring that gets a string s and returns the length of the longest substring (a run of consecutive characters) in which no character appears more than once.
Uppercase and lowercase letters are different characters, so a and A are not a repeat.
Constraints: 1 <= s.length <= 5 * 10^4. s holds only English letters (lowercase and uppercase) and digits.
Function
- arg1string
- Returnsinteger
Examples
- Input
- arg1 = "coddycode"
- Output
- 5
- Input
- arg1 = "racecar"
- Output
- 4
- Input
- arg1 = "a1b2a3b"
- Output
- 5
+12 hidden tests on Submit
Hints
Open them one at a time. Each one gives away a little more.
A substring is one continuous part of the string, so you are looking for the longest stretch you can cover without meeting the same character twice.
Keep a window with a left edge and a right edge. Grow it on the right one character at a time, and move the left edge only when the new character is already inside the window.
Store the last index where each character appeared. If the new character was last seen at or after the left edge, move the left edge to one past that index. The left edge never moves backwards, and the answer is the widest window you ever had.
A full walkthrough of this problem is on its way.
Similar problems
Problems that use the same ideas. Solving two or three of them is what makes a pattern stick.
Python
def lengthOfLongestSubstring(s):
# Write code hereCase 1
Case 2
Case 3
Input
arg1 = "coddycode"
Expected
5