Want Help Cracking FAANG?

(Then click this)

×
Back to Question Bank

1446. Consecutive Characters - Leetcode Solution

Code Implementation

class Solution:
    def maxPower(self, s: str) -> int:
        max_power = 1
        current_power = 1
        for i in range(1, len(s)):
            if s[i] == s[i-1]:
                current_power += 1
                max_power = max(max_power, current_power)
            else:
                current_power = 1
        return max_power
      
class Solution {
public:
    int maxPower(string s) {
        int max_power = 1, current_power = 1;
        for (int i = 1; i < s.size(); ++i) {
            if (s[i] == s[i-1]) {
                ++current_power;
                max_power = max(max_power, current_power);
            } else {
                current_power = 1;
            }
        }
        return max_power;
    }
};
      
class Solution {
    public int maxPower(String s) {
        int maxPower = 1, currentPower = 1;
        for (int i = 1; i < s.length(); ++i) {
            if (s.charAt(i) == s.charAt(i - 1)) {
                currentPower++;
                maxPower = Math.max(maxPower, currentPower);
            } else {
                currentPower = 1;
            }
        }
        return maxPower;
    }
}
      
var maxPower = function(s) {
    let maxPower = 1, currentPower = 1;
    for (let i = 1; i < s.length; ++i) {
        if (s[i] === s[i-1]) {
            currentPower++;
            maxPower = Math.max(maxPower, currentPower);
        } else {
            currentPower = 1;
        }
    }
    return maxPower;
};
      

Problem Description

You are given a string s consisting of only lowercase and/or uppercase English letters. Your task is to find the length of the longest substring that contains only one unique character, i.e., the maximal number of consecutive repeating characters in s.

For example, given s = "leetcode", the longest substring with consecutive repeating characters is "ee", which has length 2.

  • There is always at least one character in s.
  • Each substring considered must consist of consecutive letters in s and must have the same character.
  • Return the length as an integer.

Thought Process

At first glance, it might seem like we need to check every possible substring, but the problem specifically asks for the longest sequence of consecutive identical characters. That means we can process the string in a single pass, keeping track of sequences as we go.

The brute-force way would be to generate all possible substrings and check if all their characters are the same, but that would be inefficient. Instead, we can notice that we only need to count how long each run of repeating characters is, and keep track of the maximum.

Think of it like counting how long a "streak" of the same character lasts as you walk through the string, resetting the count whenever you see a different character.

Solution Approach

  • Initialize two variables: one to keep track of the current streak of repeating characters (current_power), and one to record the maximum found so far (max_power).
  • Start by setting both to 1, since the shortest possible streak is a single character.
  • Iterate through the string from the second character to the end.
  • For each character, check if it matches the previous character:
    • If it does, increment current_power by 1.
    • If it doesn't, reset current_power to 1.
  • After updating current_power, compare it to max_power and update max_power if needed.
  • After the loop, return max_power as the result.

This approach is efficient because it only requires a single pass through the string and uses constant extra space.

Example Walkthrough

Let's use the input s = "abbcccddddeeeeedcba".

  • Start with max_power = 1, current_power = 1.
  • At index 1, 'b' != 'a', so reset current_power = 1.
  • At index 2, 'b' == 'b', increment current_power = 2, update max_power = 2.
  • At index 3, 'c' != 'b', reset current_power = 1.
  • At index 4, 'c' == 'c', increment current_power = 2.
  • At index 5, 'c' == 'c', increment current_power = 3, update max_power = 3.
  • Continue this way: the next streaks are 4 'd's and 5 'e's, so max_power becomes 5.
  • All other streaks are shorter. The function returns 5.

The longest consecutive substring is "eeeee", so the answer is 5.

Time and Space Complexity

  • Brute-force approach: Checking all substrings would take O(N2) time and O(1) space, which is inefficient for large strings.
  • Optimized approach (used here):
    • Time Complexity: O(N), where N is the length of the input string, because we only scan the string once.
    • Space Complexity: O(1), since we only use a fixed number of variables regardless of the input size.

Summary

The key insight is to recognize that we only need to track the length of each streak of consecutive repeating characters as we scan the string. By using two variables and a single loop, we efficiently solve the problem in linear time, making the solution both simple and optimal.

This approach avoids unnecessary computation and is easy to reason about, making it an elegant solution to the "Consecutive Characters" problem.