Problem 1446

Abstract / Summary

Given a string, find the minimum number of cuts needed to split it into parts where each part has all the same character.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
14 lines | 335 bytes | submitted November 13, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 60% (300k+ submissions).

Typical patterns to solve this problem:
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 7.46 | σ = 1.18

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
32 links | 21 authors | 9 languages

Videos

11 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

6 similar problems

Solved On The Same Day

10 solutions   November 13, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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