Medium Text

Longest Substring Without Repeating Characters

Receives a string of text and returns the length of the longest run of consecutive characters that contains no repetition. It uses the sliding-window technique: a window [start..i] is kept over the text so that it never holds a repeated character, while a map remembers the last index at which each character was seen. The right edge advances one character at a time; when that character was already seen inside the current window, the left edge jumps to just past that previous occurrence, discarding the repeat in a single move instead of stepping back one position at a time. After every move the window's length is compared against the best length seen so far. The whole text is scanned once, in O(n) time, using extra space proportional to the number of distinct characters. Comparison is exact and case-sensitive; spaces and punctuation count as ordinary characters. Returns the length (a number) of the longest repetition-free substring, and 0 for an empty text.

Visualization

Input

Algorithm code

Custom input

Saved inputs

References