Python interview practice/Google
Longest Substring Without Repeating Characters
Mediumhash-table · string · sliding-window
The problem
Given a string s, find the length of the longest substring without repeating characters.
Function: def lengthOfLongestSubstring(s):
Example input (a JSON list of arguments): ["abcabcbb"]
Expected output: 3
Inputs satisfy the problem statement. Sequences contain at most 200 elements unless a smaller bound is stated. Use JSON values and the supplied function signature.
Hints
- Maintain a window with unique characters and remember each character's latest index.
- Check the supplied examples, empty/boundary cases and the stated answer policy before optimizing.
Worked answer
Try it yourself first. When you are ready, open the answer below.
Show the Python answer
def lengthOfLongestSubstring(s):
seen={}; left=best=0
for right,c in enumerate(s):
left=max(left,seen.get(c,-1)+1); seen[c]=right; best=max(best,right-left+1)
return bestWhy it works
Maintain a window with unique characters and remember each character's latest index. Advance the left bound past a repeated character only when that occurrence is still inside the window.
Complexity: O(n) time / O(min(n,alphabet)) space.
Time: O(n) time · Space: O(min(n,alphabet)) space
Run your own solution
Inside your account you write the code in the browser, run it against hidden test cases and save your attempt. Access covers every track, including the rest of Google.
See access and price