KatInterview

Longest Streak of a Repeated Character in a String

StringsAuto-graded · 22 test cases
EasyAuto-gradedStringsstringstwo-pointerslinear-scan

Last updated

Scan a string once to find the longest streak of adjacent equal characters, keeping separated streaks distinct and using only constant extra memory.

Longest Streak of a Repeated Character

You are given a string text made of ASCII characters. A streak is a non-empty stretch of consecutive positions in the string that all hold the same character. Your task is to return the length of the longest streak.

Streaks are measured independently. If the same character shows up in several places separated by other characters, those appearances are not combined. Only characters that sit directly next to each other count toward the same streak.

Comparison is exact, so uppercase and lowercase letters are different characters. Whitespace characters (spaces, tabs) are ordinary characters and can form streaks too.

If text is empty, there are no streaks, so return 0.

Aim for linear time and constant auxiliary space.

Input

  • text: a string of zero or more ASCII characters.

Output

  • An integer: the length of the longest streak of identical adjacent characters, or 0 for an empty string.

Constraints

  • 0 <= len(text) <= 10^6
  • text contains only printable ASCII characters and whitespace.
  • The solution should run in O(n) time and use O(1) extra space.

Examples

Example 1

Input: longest_streak('aabbbccccdd')

Output: 4

Example 2

Input: longest_streak('ababba')

Output: 2

Example 3

Input: longest_streak('')

Output: 0

Hints

Hint 1

Think about what you need to remember while moving left to right: how long the streak ending at the current position is, and the best length seen so far.

Hint 2

Compare each character with the one just before it. If they match, extend the current streak; otherwise the streak restarts at length 1.

Hint 3

Update the best length after every step rather than only when a streak ends, so the final streak is never missed. Handle the empty string before setting any initial values.