Ctrl K

One Typo, Most Pieces

Hard
You are given a string text of lowercase English letters and an integer limit. The string is cut into pieces like this: take the longest prefix with at most limit distinct letters, cut it off, and repeat with what is left until the string is used up. Before cutting you may replace one letter of the string with any other lowercase English letter, or leave the string as it is. Return the largest number of pieces you can get.
Example 1
text="abab", limit=2 → 2

Change the third letter to c: "abcb". It is cut into "ab" and "cb", two pieces. Without the edit the whole string is one piece.

Example 2
text="mmmm", limit=1 → 3

Change the second letter: "mzmm". The pieces are "m", "z", "mm", three in total.

Example 3
text="pqrs", limit=4 → 1
Constraints
  • 1 ≤ len(text) ≤ 10⁴
  • text consists of lowercase English letters
  • 1 ≤ limit ≤ 26
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsAssembling Fragments HardBest Word Set From Tiles HardTwo Disjoint Palindromic Picks MediumSettle Up in the Fewest Transfers HardTwo Groups With the Same Average Hard
loading Python…
Input
text="abab", limit=2
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 116 tests on the server, hidden ones included.