KatInterview

Longest Stretch of Non-Repeating Characters

StringsAuto-graded · 22 test cases
MediumAuto-gradedStringssliding-windowhash-maptwo-pointers

Last updated

Find the length of the longest contiguous run in a string where every character is distinct, using a linear-time sliding window with index tracking.

Longest Run of Distinct Characters

You are given a string text. Find the longest contiguous block of characters in which no character appears more than once, and return how long that block is.

Comparison is case-sensitive, so 'a' and 'A' are different characters. Spaces, digits, and punctuation are ordinary characters and are treated like any other.

A block must be contiguous, meaning a run of neighbouring characters. Picking characters that are not adjacent (a subsequence) does not count.

Input

  • text: a string of length n.

Output

  • An integer: the length of the longest contiguous block of text whose characters are all different.
  • If text is empty, return 0.

Constraints

  • 0 <= len(text) <= 10^5
  • text contains English letters, digits, symbols, and spaces (printable ASCII).
  • The solution should run in O(n) time.
  • Extra space should be O(min(n, m)), where m is the size of the character set (at most 128).

Examples

Example 1

Input: longest_distinct_run('abcabcbb')

Output: 3

Example 2

Input: longest_distinct_run('bbbbb')

Output: 1

Example 3

Input: longest_distinct_run('pwwkew')

Output: 3

Example 4

Input: longest_distinct_run('')

Output: 0

Hints

Hint 1

Think of a window over the string that you grow one character at a time on the right. What must stay true about the characters inside it?

Hint 2

Store, for each character, the last index at which you saw it. When the new character was already seen inside the current window, the window's left edge must move to just after that earlier position.

Hint 3

Be careful with stale entries: a character's recorded index may lie before the window's left edge, in which case it must not move the left edge. The left edge should never move backward (try `"abba"`).