First, you are allowed to change at mostone index in s to another lowercase English letter.
After that, do the following partitioning operation until s is empty:
Choose the longestprefix of s containing at most kdistinct characters.
Delete the prefix from s and increase the number of partitions by one. The remaining characters (if any) in s maintain their initial order.
Return an integer denoting the maximum number of resulting partitions after the operations by optimally choosing at most one index to change.
Example 1:
Input:s = "accca", k = 2
Output:3
Explanation:
The optimal way is to change s[2] to something other than a and c, for example, b. then it becomes "acbca".
Then we perform the operations:
The longest prefix containing at most 2 distinct characters is "ac", we remove it and s becomes "bca".
Now The longest prefix containing at most 2 distinct characters is "bc", so we remove it and s becomes "a".
Finally, we remove "a" and s becomes empty, so the procedure ends.
Doing the operations, the string is divided into 3 partitions, so the answer is 3.
Example 2:
Input:s = "aabaab", k = 3
Output:1
Explanation:
Initially s contains 2 distinct characters, so whichever character we change, it will contain at most 3 distinct characters, so the longest prefix with at most 3 distinct characters would always be all of it, therefore the answer is 1.
Example 3:
Input:s = "xxyz", k = 1
Output:4
Explanation:
The optimal way is to change s[0] or s[1] to something other than characters in s, for example, to change s[0] to w.
Then s becomes "wxyz", which consists of 4 distinct characters, so as k is 1, it will divide into 4 partitions.
Problem summary: You are given a string s and an integer k. First, you are allowed to change at most one index in s to another lowercase English letter. After that, do the following partitioning operation until s is empty: Choose the longest prefix of s containing at most k distinct characters. Delete the prefix from s and increase the number of partitions by one. The remaining characters (if any) in s maintain their initial order. Return an integer denoting the maximum number of resulting partitions after the operations by optimally choosing at most one index to change.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Dynamic Programming · Bit Manipulation
Example 1
"accca"
2
Example 2
"aabaab"
3
Example 3
"xxyz"
1
Related Problems
Can Make Palindrome from Substring (can-make-palindrome-from-substring)
Step 02
Core Insight
What unlocks the optimal approach
For each position, try to brute-force the replacements.
To speed up the brute-force solution, we can precompute the following (without changing any index) using prefix sums and binary search:<ul> <li><code>pref[i]</code>: The number of resulting partitions from the operations by performing the operations on <code>s[0:i]</code>.</li> <li><code>suff[i]</code>: The number of resulting partitions from the operations by performing the operations on <code>s[i:n - 1]</code>, where <code>n == s.length</code>.</li> <li><code>partition_start[i]</code>: The start index of the partition containing the <code>i<sup>th</sup></code> index after performing the operations.</li> </ul>
Now, for a position <code>i</code>, we can try all possible <code>25</code> replacements:<br /> For a replacement, using prefix sums and binary search, we need to find the rightmost index, <code>r</code>, such that the number of distinct characters in the range <code>[partition_start[i], r]</code> is at most <code>k</code>.<br /> There are <code>2</code> cases:<ul> <li><code>r >= i</code>: the number of resulting partitions in this case is <code>1 + pref[partition_start[i] - 1] + suff[r + 1]</code>.</li> <li>Otherwise, we need to find the rightmost index <code>r<sub>2</sub></code> such that the number of distinct characters in the range <code>[r:r<sub>2</sub>]</code> is at most <code>k</code>. The answer in this case is <code>2 + pref[partition_start[i] - 1] + suff[r<sub>2</sub> + 1]</code></li> </ul>
The answer is the maximum among all replacements.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3003: Maximize the Number of Partitions After Operations
class Solution {
private Map<List<Integer>, Integer> f = new HashMap<>();
private String s;
private int k;
public int maxPartitionsAfterOperations(String s, int k) {
this.s = s;
this.k = k;
return dfs(0, 0, 1);
}
private int dfs(int i, int cur, int t) {
if (i >= s.length()) {
return 1;
}
var key = List.of(i, cur, t);
if (f.containsKey(key)) {
return f.get(key);
}
int v = 1 << (s.charAt(i) - 'a');
int nxt = cur | v;
int ans = Integer.bitCount(nxt) > k ? dfs(i + 1, v, t) + 1 : dfs(i + 1, nxt, t);
if (t > 0) {
for (int j = 0; j < 26; ++j) {
nxt = cur | (1 << j);
if (Integer.bitCount(nxt) > k) {
ans = Math.max(ans, dfs(i + 1, 1 << j, 0) + 1);
} else {
ans = Math.max(ans, dfs(i + 1, nxt, 0));
}
}
}
f.put(key, ans);
return ans;
}
}
// Accepted solution for LeetCode #3003: Maximize the Number of Partitions After Operations
func maxPartitionsAfterOperations(s string, k int) int {
n := len(s)
type tuple struct{ i, cur, t int }
f := map[tuple]int{}
var dfs func(i, cur, t int) int
dfs = func(i, cur, t int) int {
if i >= n {
return 1
}
key := tuple{i, cur, t}
if v, ok := f[key]; ok {
return v
}
v := 1 << (s[i] - 'a')
nxt := cur | v
var ans int
if bits.OnesCount(uint(nxt)) > k {
ans = dfs(i+1, v, t) + 1
} else {
ans = dfs(i+1, nxt, t)
}
if t > 0 {
for j := 0; j < 26; j++ {
nxt = cur | (1 << j)
if bits.OnesCount(uint(nxt)) > k {
ans = max(ans, dfs(i+1, 1<<j, 0)+1)
} else {
ans = max(ans, dfs(i+1, nxt, 0))
}
}
}
f[key] = ans
return ans
}
return dfs(0, 0, 1)
}
# Accepted solution for LeetCode #3003: Maximize the Number of Partitions After Operations
class Solution:
def maxPartitionsAfterOperations(self, s: str, k: int) -> int:
@cache
def dfs(i: int, cur: int, t: int) -> int:
if i >= n:
return 1
v = 1 << (ord(s[i]) - ord("a"))
nxt = cur | v
if nxt.bit_count() > k:
ans = dfs(i + 1, v, t) + 1
else:
ans = dfs(i + 1, nxt, t)
if t:
for j in range(26):
nxt = cur | (1 << j)
if nxt.bit_count() > k:
ans = max(ans, dfs(i + 1, 1 << j, 0) + 1)
else:
ans = max(ans, dfs(i + 1, nxt, 0))
return ans
n = len(s)
return dfs(0, 0, 1)
// Accepted solution for LeetCode #3003: Maximize the Number of Partitions After Operations
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3003: Maximize the Number of Partitions After Operations
// class Solution {
// private Map<List<Integer>, Integer> f = new HashMap<>();
// private String s;
// private int k;
//
// public int maxPartitionsAfterOperations(String s, int k) {
// this.s = s;
// this.k = k;
// return dfs(0, 0, 1);
// }
//
// private int dfs(int i, int cur, int t) {
// if (i >= s.length()) {
// return 1;
// }
// var key = List.of(i, cur, t);
// if (f.containsKey(key)) {
// return f.get(key);
// }
// int v = 1 << (s.charAt(i) - 'a');
// int nxt = cur | v;
// int ans = Integer.bitCount(nxt) > k ? dfs(i + 1, v, t) + 1 : dfs(i + 1, nxt, t);
// if (t > 0) {
// for (int j = 0; j < 26; ++j) {
// nxt = cur | (1 << j);
// if (Integer.bitCount(nxt) > k) {
// ans = Math.max(ans, dfs(i + 1, 1 << j, 0) + 1);
// } else {
// ans = Math.max(ans, dfs(i + 1, nxt, 0));
// }
// }
// }
// f.put(key, ans);
// return ans;
// }
// }
// Accepted solution for LeetCode #3003: Maximize the Number of Partitions After Operations
function maxPartitionsAfterOperations(s: string, k: number): number {
const n = s.length;
const f: Map<bigint, number> = new Map();
const dfs = (i: number, cur: number, t: number): number => {
if (i >= n) {
return 1;
}
const key = (BigInt(i) << 27n) | (BigInt(cur) << 1n) | BigInt(t);
if (f.has(key)) {
return f.get(key)!;
}
const v = 1 << (s.charCodeAt(i) - 97);
let nxt = cur | v;
let ans = 0;
if (bitCount(nxt) > k) {
ans = dfs(i + 1, v, t) + 1;
} else {
ans = dfs(i + 1, nxt, t);
}
if (t) {
for (let j = 0; j < 26; ++j) {
nxt = cur | (1 << j);
if (bitCount(nxt) > k) {
ans = Math.max(ans, dfs(i + 1, 1 << j, 0) + 1);
} else {
ans = Math.max(ans, dfs(i + 1, nxt, 0));
}
}
}
f.set(key, ans);
return ans;
};
return dfs(0, 0, 1);
}
function bitCount(i: number): number {
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16);
return i & 0x3f;
}
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n × |\Sigma| × k)
Space
O(n × |\Sigma| × k)
Approach Breakdown
RECURSIVE
O(2ⁿ) time
O(n) space
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.