Consecutive Characters - Problem

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

Given a string s, return the power of s.

For example, if s = "leetcode", the power is 2 because the substring "ee" has length 2 and contains only the character 'e'.

Input & Output

Example 1 — Basic Case
$ Input: s = "leetcode"
Output: 2
💡 Note: The substring "ee" has length 2 with all characters identical. This is the longest such substring.
Example 2 — Single Character
$ Input: s = "abbcccddddeeeeedcba"
Output: 5
💡 Note: The substring "eeeee" has length 5 with all characters identical.
Example 3 — All Same
$ Input: s = "aaaa"
Output: 4
💡 Note: The entire string consists of identical characters, so the power is the length of the string.

Constraints

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

Visualization

Tap to expand
Consecutive Characters - Power of String INPUT String s = "leetcode" l 0 e 1 e 2 t 3 c 4 o 5 d 6 consecutive Input Values s = "leetcode" length = 8 Find max consecutive same characters ALGORITHM STEPS 1 Initialize maxPower=1, count=1 2 Iterate string Compare s[i] with s[i-1] 3 If same char count++, else count=1 4 Update max maxPower = max(max, cnt) Trace Example i=1: e==l? No cnt=1 max=1 i=2: e==e? Yes cnt=2 max=2 i=3: t==e? No cnt=1 max=2 i=4: c==t? No cnt=1 max=2 ... FINAL RESULT Maximum consecutive run found: e e Two consecutive 'e's at index 1-2 Output 2 OK - Power = 2 Time: O(n), Space: O(1) l[ee]tcode --> power = 2 Key Insight: Single pass approach: Track consecutive character count by comparing current char with previous. If chars match, increment counter; otherwise reset to 1. Update maximum at each step. This achieves O(n) time with O(1) space - optimal solution using sliding window concept. TutorialsPoint - Consecutive Characters | Optimal Solution
Asked in
Google 15 Facebook 12 Amazon 8
28.5K Views
Medium Frequency
~15 min Avg. Time
980 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen