top of page

Consecutive Characters (LeetCode 1446): Tracking the Longest Run

Nov 4
1 min read

The power of a string is the length of its longest substring made of a single repeated character. Return it. This is the classic 'run length' scan that shows up inside many harder problems.

Approach

Walk the string keeping the length of the current run. When the character matches the previous one, extend the run; otherwise reset it to 1. Track the best run seen so far.

def max_power(s):

best = cur = 1

for i in range(1, len(s)):

cur = cur + 1 if s[i] == s[i - 1] else 1

best = max(best, cur)

return best

Complexity

O(n) time and O(1) extra space.

Interview pitfalls

Initialize best to 1, not 0, because a non-empty string always has power at least 1. Mention that itertools.groupby gives a one-liner, then show the loop.

Practicing out loud

The hard part of easy problems is explaining them crisply under time pressure. Practice narrating the approach, the complexity and one edge case in under a minute. Disclosure: I work on Linkjob AI, a real-time interview assistant. If you want live practice help, see AI tool for job interviews.

 
 
 

Recent Posts

See All
Image Smoother (LeetCode 661): Clean Neighbor Loops

For each cell of a grayscale image, replace it with the floor of the average of itself and its up to eight neighbors. Idea Loop over the 3x3 block around each cell, skip coordinates outside the grid,

 
 
 

Comments


bottom of page