We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Consecutive Characters

Number: 1542

Difficulty: Easy

Paid? No

Companies: Goldman Sachs, Meta


Problem Description

Given a string s, determine its "power"—the length of the longest contiguous substring that contains only one unique character. In other words, find the maximum number of consecutive identical characters in the string.


Key Insights

  • The problem can be solved by scanning the string once.
  • Keep track of the current streak of identical characters and update the maximum when the streak is broken or extended.
  • A linear traversal yields an efficient O(n) solution.

Space and Time Complexity

Time Complexity: O(n) - where n is the length of the string, as we make one pass. Space Complexity: O(1) - uses only a few extra variables.


Solution

We use a simple iteration through the string to count consecutive characters. Two main variables are maintained: one for the current count of identical consecutive characters and one for the maximum count found so far. As we iterate, if the current character matches the previous one, the current count is incremented; otherwise, it is reset to 1. This method ensures we capture the longest substring of identical characters in one pass.


Code Solutions

# Function to calculate the maximum power of the string
def max_power(s):
    # Initialize the maximum power and the current count with 1
    max_power = 1
    current_count = 1
    
    # Iterate through the string starting from the second character
    for i in range(1, len(s)):
        # If the current character is equal to the previous, increment the count
        if s[i] == s[i-1]:
            current_count += 1
            # Update the maximum power if current streak is greater
            max_power = max(max_power, current_count)
        else:
            # Reset the count when consecutive sequence breaks
            current_count = 1
    return max_power

# Example usage:
# result = max_power("abbcccddddeeeeedcba")
# print(result)  # Output: 5
← Back to All Questions