Skip to main content

Consecutive Characters - Solution & Explanation

EasyString10 min readAsked at: Amazon, Goldman Sachs, Meta +1
Practice this problem

Problem Statement

The power of the string is the maximum length of a non-empty substring that contains only one unique character.

Given a string s, return the power of s.

 

Example 1:

Input: s = "leetcode"
Output: 2
Explanation: The substring "ee" is of length 2 with the character 'e' only.

Example 2:

Input: s = "abbcccddddeeeeedcba"
Output: 5
Explanation: The substring "eeeee" is of length 5 with the character 'e' only.

 

Constraints:

  • 1 <= s.length <= 500
  • s consists of only lowercase English letters.

Approach Overview

Problem Overview: Given a string s, return the length of the longest substring that contains only one repeating character. The task is essentially to compute the maximum run length of identical characters while scanning the string.

This problem belongs to the string processing category and is often used to test whether you can efficiently track patterns while iterating through characters.

Approach 1: Sliding Window / Linear Scan (O(n) time, O(1) space)

The optimal approach scans the string once while tracking the current streak of identical characters. Start with two variables: currentCount for the length of the current run and maxCount for the best result seen so far. Iterate through the string from index 1. If the current character matches the previous character, increment currentCount. Otherwise reset currentCount to 1 because a new character sequence begins. After each step, update maxCount = max(maxCount, currentCount).

This method behaves like a simplified sliding window where the window expands while characters match and resets when they change. Since each character is processed exactly once, the algorithm runs in O(n) time with O(1) extra space. This is the most common and practical solution for the problem.

Approach 2: Recursive Approach with Memoization (O(n) time, O(n) space)

You can also solve the problem using recursion by defining a function that computes the longest run ending at a given index. If s[i] == s[i-1], the run length becomes 1 + f(i-1); otherwise it resets to 1. Memoization stores results for each index so repeated computations are avoided.

While this version still processes each index once, recursion introduces stack overhead and requires an auxiliary memo array or dictionary, resulting in O(n) space usage. The logic mirrors the iterative scan but expresses it in a top‑down dynamic style. This approach can be useful when practicing recursion patterns or when building intuition about state transitions across indices.

Recommended for interviews: The sliding window / linear scan approach is what interviewers expect. It demonstrates that you can detect contiguous patterns while iterating through a string and maintain constant space. The recursive version shows conceptual understanding, but the iterative O(n) scan is cleaner, faster, and typically preferred in production code.

Approach 1: Sliding Window Approach

The Sliding Window approach iterates through the string keeping track of the current character streak. When the character changes, update the maximum streak length if the current streak is larger. Reset the current streak counter for the new character.

The code initializes two counters: max_power and current_power. As it iterates through the string, if consecutive characters are identical, it increments current_power. If not, it updates max_power if current_power exceeds it, and resets current_power.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n) since each character is processed once.
Space Complexity: O(1) as no extra space is used aside from variables.

Try this approach in the editor →

Approach 2: Recursive Approach with Memoization

The recursive approach utilizes memoization to avoid repetitive calculations as it navigates the string, exploring all possibilities for consecutive substrings.

Python's recursive solution uses a cache to store already computed results, progressively calculating the power from the leftmost to the rightmost position of the string. It returns the maximum possible achieved by counting same consecutive characters.

Code

Python

JavaScript

Complexity

Time Complexity: O(n)
Space Complexity: O(n) due to recursion call stack and cache storage.

Try this approach in the editor →

Approach 3: Traversal and Counting

We define a variable t to represent the length of the current consecutive characters, initially t=1.

Next, we traverse the string s starting from the second character. If the current character is the same as the previous character, then t = t + 1, and update the answer ans = max(ans, t); otherwise, set t = 1.

Finally, return the answer ans.

The time complexity is O(n), where n is the length of the string s. The space complexity is O(1).

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Sliding Window Approach

Time Complexity: O(n) since each character is processed once.
Space Complexity: O(1) as no extra space is used aside from variables.

Recursive Approach with Memoization

Time Complexity: O(n)
Space Complexity: O(n) due to recursion call stack and cache storage.

Traversal and Counting

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Sliding Window / Linear ScanO(n)O(1)Best general solution when scanning strings for consecutive patterns
Recursive with MemoizationO(n)O(n)Useful for practicing recursion or dynamic state transitions across indices

Video Solution

Consecutive Characters | LeetCode 1446 | C++, Java, PythonKnowledge Center13,537 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Consecutive Characters easy or hard?
Consecutive Characters is classified as an Easy problem on LeetCode with an acceptance rate around 60%. It focuses on basic string iteration and maintaining a running count, making it a common warm‑up question for string manipulation problems.
Consecutive Characters Python/Java solution
Both Python and Java implementations follow the same logic: iterate through the string, compare each character with the previous one, update a running count, and maintain the maximum streak. The implementation requires only a loop and two integer variables, giving O(n) time and O(1) space complexity.
How to solve Consecutive Characters in O(n)?
Iterate through the string while maintaining a counter for the current sequence of identical characters. If s[i] equals s[i-1], increment the counter; otherwise reset it to 1. Track the maximum value seen during the scan. Since every character is processed once, the solution runs in O(n) time with constant extra space.
What is the best approach for Consecutive Characters?
The best approach is a sliding window or simple linear scan that tracks the current streak of identical characters while iterating through the string. Each time the current character matches the previous one, increase the streak; otherwise reset it to 1. This method runs in O(n) time and O(1) space, making it optimal for this problem.
Is Consecutive Characters asked at Google/Amazon/Meta?
Consecutive character streak problems appear frequently in coding interviews because they test basic string traversal and pattern detection. Variations of this question have been reported in interviews at companies like Amazon and other large tech firms, especially in early technical rounds.
What data structure is used in Consecutive Characters?
The problem mainly relies on string traversal and simple counters rather than complex data structures. The algorithm scans the string sequentially and keeps track of the current consecutive character count and the maximum count encountered.
What is the time complexity of Consecutive Characters?
The optimal solution runs in O(n) time where n is the length of the string. Each character is visited exactly once during the scan. Space complexity is O(1) because only a few counters are used to track the current run and the maximum length.

Ready to solve this problem?

Practice Consecutive Characters with our built-in code editor and test cases.

Practice on FleetCode