Challenge: Longest Unique Stretch
Completed
Read a word and print the length of the longest stretch of neighbouring letters with no letter repeated.
Input
One word (letters only, at least 1 letter).
Output
One number.
Example
Input
abcabcbb
Output
3
Editor
Python
Hints
Keep the letters in the window in a set.
If the new letter is already in the set, remove letters from the left until it isn't.
Solution explanation
Each letter enters and leaves the window at most once, so the total work is O(n).
Show solution
s = input().strip()
seen = set()
left = best = 0
for right in range(len(s)):
while s[right] in seen:
seen.remove(s[left])
left += 1
seen.add(s[right])
best = max(best, right - left + 1)
print(best) Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module