48. Longest Substring Without Repeats
Difficulty: Medium · Topic: DSA for data engineers
Write longest_unique(s): the length of the longest substring of s (a run of consecutive characters) in which no character repeats. It must be O(n): strings can be 200,000 characters long.
Your code runs in CPython on our servers against 7 tests, including hidden ones.
Sample test
longest_unique("abcabcbb")Expected: 3
Hints
Hint 1
Keep a window[start, i] with no repeats and grow it one character at a time.Hint 2
Remember each character's last index. When the new character was last seen inside the window, movestart just past that position.Hint 3
Never movestart backwards: a repeat that is already outside the window does not matter.Learn the concepts
- Lists, dicts and sets: what each operation costs · 7 min read. Pick the container from the question, and why a set turns an hour-long loop into a second.
- Sliding windows, sweeps and binary search · 5 min read. O(n) windows, sort-then-sweep for intervals, and bisect for as-of lookups.
More Python problems
- Two Sum · Easy
- Valid Brackets · Easy
- First Non-Repeating Character · Easy
- Group Anagrams · Medium
- Top K Frequent with a Heap · Medium
- Latest Event at or Before a Time · Medium
- Merge K Sorted Linked Lists · Hard
- Task Order with Cycle Detection · Hard