KatInterview

Longest Run With No Repeated Character

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

Last updated

Find the length of the longest contiguous block of a string with no repeated character, using a linear-time sliding window with exact, case-sensitive comparison.

You are given a string text. Find the largest possible length of a contiguous piece of text in which no character occurs more than once.

A piece is contiguous if it consists of neighbouring characters taken in their original order. Selecting characters that are not adjacent in text does not count. The empty piece is allowed, so an empty text gives the answer 0.

Details

  • Characters are compared exactly as they appear. An uppercase letter and its lowercase version are two different characters.
  • Spaces, digits and punctuation marks are ordinary characters and may repeat just like letters.
  • Several different pieces may reach the maximum length. Only that length is required.

Function

Implement longest_unique_run(text), which returns a single integer: the length of the longest repeat-free contiguous piece of text.

Constraints

  • 0 <= len(text) <= 50000
  • Every character of text is printable ASCII (codes 32 through 126), including the space.
  • Since only 95 distinct characters exist, the answer is at most min(len(text), 95).

Examples

Example 1

Input: longest_unique_run('streets')

Output: 4

Example 2

Input: longest_unique_run('aAbBa')

Output: 4

Example 3

Input: longest_unique_run('')

Output: 0

Hints

Hint 1

Start with brute force: test every substring for repeats. Then ask why that wastes work when two neighbouring substrings overlap almost entirely.

Hint 2

Maintain a window [left, i] that is always repeat-free. When you add text[i], the only possible conflict is an earlier copy of that same character.

Hint 3

Store the most recent index of each character. If that index lies inside the current window, move left to just past it; if it lies before left, ignore it, since otherwise left could move backwards (try "abba").