Longest Substring Without Repeating Characters
1Try it yourself first
Think for 20-30 minutes before you open any hint. Being stuck is where the learning happens.
Only for you, saved in this browser. After you see the approach you will compare it with your idea.2What is being asked
Find the length of the longest stretch of characters in which no character repeats.
3Hint ladder
Take one rung at a time. Stop as soon as the idea clicks.
- Hint 1When a character repeats, how far must the window's left edge move?
- Hint 2Remember the last position of each character.
4The approach
Have you tried the hints? The approach is built as a path from the obvious way to the clever one.
A photographer frames a row of people so that nobody wears the same colour twice. A new person walks into the right of the frame wearing a colour already inside. Fix: slide the left edge of the frame forward until that earlier person with the same colour is out. The widest valid frame over the whole row is the answer. For speed, remember where each colour was last seen so the left edge can jump straight past it.
- The obvious way
Check every substring for duplicates: O(n³), or O(n²) with a set.
- The key insight
Keep a window with no repeats. When the new character was last seen inside the window, move the left edge to just after that earlier spot, in one jump, no removals one by one. Note the window width at every step.
- The algorithm
- Notebook: last position of every character. Left edge at the start. Best = 0.
- Take the next character at the right edge.
- Was it last seen inside the window? Move the left edge to just after that spot.
- Write down its new position; best = max(best, window width).
Watch it run
Exampletext = "abcabcbb"
a, b, c walk in: no repeats, window "abc", width 3.
best 3
Where people slip
- Only jump the left edge if the earlier occurrence is INSIDE the window (>= left); otherwise left would move backwards.
How close was your idea?
You did not write an idea, and that is fine.
Be honest with yourself. This sets your revision list.
5Code
Try writing it yourself from the steps first. Then compare.
def length_of_longest_substring(text):
last_seen = {} # character -> last position
left = 0 # left edge of the window
best = 0
for right, character in enumerate(text):
if last_seen.get(character, -1) >= left: # repeat inside the window
left = last_seen[character] + 1 # jump past the earlier one
last_seen[character] = right
best = max(best, right - left + 1)
return bestNow close this and write it again from memory, in the language you will use in the interview. Reattempt after 1 day, 7 days and about 30 days.
6Still stuck? Watch a video
Seeing someone explain it out loud can make it click. Try the video after you have read the approach above.