Consecutive Characters (LeetCode 1446): Solution and Explanation

Easy
String

The power of a string is the length of its longest block of one repeated letter. Walk the string once, growing a run counter while the letter repeats and resetting it when the letter changes; the largest run seen is the answer. "abbcccddddeeeeedcba" has power 5 from "eeeee".

Intuition

A substring with one distinct letter is a stretch of equal adjacent letters, so the string splits into runs and the answer is the longest one.

Each run can be measured while walking past it: compare s[i] with s[i - 1] and either extend or restart.

Only two numbers matter at any moment: the length of the current run and the best length so far.

Approach: One pass with a run counter

  1. Set run = best = 1, since the first letter alone is a run of length 1.
  2. For each i from 1: if s[i] == s[i - 1], increment run and set best = max(best, run).
  3. Otherwise the letter changed, so reset run = 1.
  4. Return best.

Step-by-step example

s = "leetcode"
  1. l starts a run of 1; best = 1.
  2. e differs from l: run resets to 1.
  3. e repeats e: run = 2, best = 2.
  4. t, c, o, d, e each differ from the previous letter, so run keeps resetting to 1.
  5. The loop ends and the answer is best = 2.

Code: Python, Java, C++

1class Solution:
2    def maxPower(self, s: str) -> int:
3        best = run = 1
4        for i in range(1, len(s)):
5            if s[i] == s[i - 1]:
6                run += 1
7                best = max(best, run)
8            else:
9                run = 1
10        return best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Every letter is compared with its neighbor once.

Space

O(1)

Only the two counters are stored.

Other approaches

Two pointers over runs (time O(n), space O(1))

Let j jump forward from i while s[j] == s[i], record j - i, then set i = j. Same pass, measured one whole run at a time.

Group by consecutive keys (time O(n), space O(n))

In Python, max(len(list(g)) for _, g in itertools.groupby(s)) measures every run directly. Short, but allocates each group.

Common mistakes

  • Starting best at 0. A string of all different letters has power 1, not 0.
  • Updating best only when the run breaks, which misses a longest run that reaches the end of the string.
  • Counting total occurrences of a letter instead of adjacent occurrences.

Frequently asked questions

Why update best inside the repeat branch?

Because run only grows there. Updating at that point also covers a run that ends at the last letter, so no extra check after the loop is needed.

How does this relate to Max Consecutive Ones?

It is the same run counter. Max Consecutive Ones only counts runs of 1, while here any repeated letter counts.