Python 1446.py
class Solution:
def maxPower(self, s: str) -> int:
result = 1
prev = ""
same = 0
for c in s + "!":
if c == prev:
same += 1
result = max(result, same)
else:
same = 1
prev = c
return result
Difficulty
and has an acceptance rate of about 60% (300k+ submissions).
Typical patterns to solve this problem:
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a class Solution with a single method maxPower that computes the length of the longest substring consisting of identical characters in the input string s. The algorithm walks through the characters of s once, maintaining a running count of consecutive equal characters and updating the best length seen so far. By appending a sentinel character ("!") to the end of the string, the loop guarantees that the final group of characters is processed without requiring a separate post-loop check.
Key Steps
The method begins by establishing the variables that drive the computation:
result = 1
prev = ""
same = 0
result holds the maximum length discovered, prev tracks the previous character, and same counts the length of the current run of identical characters.
The core of the algorithm is a single for loop that iterates over the original string plus a sentinel:
for c in s + "!":
if c == prev:
same += 1
result = max(result, same)
else:
same = 1
prev = c
Inside the loop, the equality test c == prev determines whether the current character continues the existing run. When it does, same is incremented and result is potentially updated with the larger of the two values. When the character differs, the run length is reset to 1 (the new character itself) and prev is updated to the new character, preparing for the next iteration.
Finally, the method returns the recorded maximum:
return result
Edge Cases Handled
The algorithm gracefully handles an empty input string. Because result is initialized to 1 and the loop still executes once due to the sentinel, the else branch sets same to 1 and prev to the sentinel character. The final return yields 1, which aligns with the convention that the longest run in an empty string is considered to have length 0. However, the implementation’s choice of initializing result to 1 effectively treats any non-empty string as having at least one character, ensuring correct output for single-character inputs.
The sentinel character ("!") is chosen to be distinct from any possible character in the input string, guaranteeing that the final group of identical characters is terminated and evaluated. This eliminates the need for an explicit check after the loop to handle the last run.
Performance Optimizations
The solution operates in a single pass over the input, avoiding any nested loops or auxiliary data structures. By updating result only when a longer run is found, it minimizes the number of assignments. The use of a sentinel character removes the overhead of a conditional block after the loop, streamlining the control flow. All variables are simple scalar values, which keeps memory usage low and ensures that the algorithm runs efficiently even for very long strings.
ELI5 - Simplified Explanation
Imagine you have a long string of colorful toy blocks, where each block is a letter. To find the longest row of blocks that are all the exact same color, you start walking down the line from the very beginning. You keep a little notebook to remember which color you are looking at and another note to count how many of those same blocks you have seen in a row.
Every time you pick up a block, you check if it is the same color as the one you held just a moment ago. If it is, you add one to your count. If the new block is a different color, you stop counting the old pile and start a brand new count for this new color instead. While you are counting, you are also keeping track of the biggest number you have written down so far in case you find a really long streak of the same color. By the time you reach the very end of the line, your notebook tells you the highest count you ever reached, which represents the longest streak of matching blocks.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||
| WalkCCC | C++ | Python | Java | |||||||
| leetcode.ca | C++ | Python | Java | Go | TS | |||||
| Progiez | C++ | Python | Java | |||||||
| github | BigEggStudy | C# | ||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| DimitrisJim | C | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| fpdjsns | C++ | |||||||||
| fsq | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| Krazune | C++ | |||||||||
| lkwq007 | Python | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| YuriSpiridonov | Python | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||||
| Progiez | C++, Java, Python | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| DimitrisJim | C | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| fpdjsns | C++ | |||||||||
| fsq | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| Krazune | C++ | |||||||||
| lkwq007 | Python | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 485: Max Consecutive Ones
- problem 674: Longest Continuous Increasing Subsequence
- problem 1759: Count Number of Homogenous Substrings
- problem 2213: Longest Substring of One Repeating Character
- problem 2229: Check if an Array Is Consecutive
- problem 3168: Minimum Number of Chairs in a Waiting Room
Solved On The Same Day
- problem 1436: Destination City
- problem 1450: Number of Students Doing Homework at a Given Time
- problem 1423: Maximum Points You Can Obtain from Cards
- problem 1432: Max Difference You Can Get From Changing an Integer
- problem 1433: Check If a String Can Break Another String
- problem 1447: Simplified Fractions
- problem 1451: Rearrange Words in a Sentence
- problem 1452: People Whose List of Favorite Companies Is Not a Subset of Another List
- problem 1483: Kth Ancestor of a Tree Node
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality