KatInterview

Longest Run Using No More Than Two Letter Kinds

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

Last updated

Find the longest contiguous stretch of a string containing at most two different characters, testing the sliding window technique with a frequency map.

Longest Two-Character Stretch

You are given a string text. A stretch is any block of consecutive characters taken from text. Your task is to determine how long the longest stretch can be, given that it may contain no more than two different characters.

Rules

  • Characters are compared exactly as they appear, so uppercase and lowercase letters are different characters ('a' and 'A' count as two kinds).
  • A stretch that uses only one kind of character is also allowed.
  • If text is empty, the answer is 0.

Input

  • text: a string made up of printable ASCII characters.

Output

  • An integer: the length of the longest stretch of text that contains at most two distinct characters.

Constraints

  • 0 <= len(text) <= 10^5
  • text contains only printable ASCII characters.
  • The expected solution runs in linear time in len(text).

Examples

Example 1

Input: longest_two_kind_stretch('eceba')

Output: 3

Example 2

Input: longest_two_kind_stretch('ccaabbb')

Output: 5

Example 3

Input: longest_two_kind_stretch('')

Output: 0

Example 4

Input: longest_two_kind_stretch('abababab')

Output: 8

Hints

Hint 1

If a stretch already has at most two distinct characters, any smaller stretch inside it is also valid. That suggests growing a window and only trimming it when it becomes invalid.

Hint 2

Keep two indices, a left and a right edge, plus a dictionary of how many times each character appears inside the window. Move the right edge one step at a time and add the new character.

Hint 3

When the dictionary holds more than two keys, advance the left edge, decrementing counts and deleting a key as soon as its count reaches zero. After restoring validity, record the window length.