◀ THE GRIND — SLIDING WINDOW

Longest Substring Without Repeating Characters

MEDIUM✓ CHIP-TIMEDLC #3 — FULL STATEMENT ↗

The drill: Hunt the longest stretch of a string in which no character appears twice. The answer is just a length — the fight is keeping the window legal without restarting from scratch at every collision.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

A string of characters arrives, and the task is to find the length of the longest contiguous stretch within it where no character shows up more than once.

Only the length is reported, not the substring itself, and there can be many different stretches that tie for that longest length — any one of them proves the answer correct.

Case matters, so an uppercase and lowercase version of the same letter count as different characters, and the string can include digits, symbols, or spaces alongside letters.

EX 01
s = "racecar"
4
BEST RUN IS THE FRONT FOUR
EX 02
s = ""
0
EMPTY STRING
EX 03
s = "aaaa"
1
ONE LETTER OVER AND OVER
THE HINTS — TAKE ONLY WHAT YOU NEED
HINT 1 THE NUDGE

Restarting the scan after every collision throws away everything you learned. When a repeat shows up, how much of the current window is actually poisoned?

HINT 2 THE STRUCTURE

Only the prefix up to and including the earlier copy is dead — everything after it is still repeat-free. Two pointers can keep that part alive.

HINT 3 ONE STEP FROM THE ANSWER

Slide with a char→last-index map: when the incoming character was last seen inside the window, jump the left edge to just past that old copy. Length is right − left + 1, every step.

COACH'S BOARD — THE PATTERN, STEP BY STEP
THE LAST-SEEN LEAPPATTERN · SLIDING WINDOW + LAST SEENs = "abba"
a
b
b
a
LAST SEEN INDEX
— empty —
STEP 1

Right pointer starts at 0, left at 0 — the map remembers each character's last seen index.

STEP 1 / 6 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/longest-substring-without-repeating-characters.pyRACE PACE
LANG ▸
PACE ▸
class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        last = {}  # char -> most recent index
        best = 0
        left = 0
        for right, ch in enumerate(s):
            if ch in last and last[ch] >= left:
                left = last[ch] + 1     # leap past the stale copy
            last[ch] = right
            best = max(best, right - left + 1)
        return best
TIME O(N)SPACE O(MIN(N, Α))PYTHON · RACE PACE · 11 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED