Maximum Valid-Partition Block Count for Every Prefix
Dynamic ProgrammingModel answerLast updated
For each prefix of a string, find the maximum number of contiguous blocks it can be split into where every character in a block shares the same frequency.
Problem
You are given a string s of lowercase English letters. A uniform block is a non-empty contiguous substring where every character that appears in it occurs the same number of times. For example, "aabb" is a uniform block ('a' and 'b' each appear twice), and "a" is a uniform block (one character, one occurrence).
A prefix s[0..k-1] is splittable if it can be written as a concatenation of one or more uniform blocks placed end-to-end with no gaps and no overlaps.
Implement max_uniform_splits(s) that returns a list of len(s) integers. The i-th value (0-indexed) is the maximum number of uniform blocks the prefix of length i+1 can be partitioned into, or 0 if no valid partition exists.
def max_uniform_splits(s: str) -> List[int]:
Constraints
1 <= len(s) <= 2000sconsists of lowercase English letters only.
Examples
Example 1
Input: s = "aabbcc"
Output: [1, 2, 3, 4, 5, 6]
Explanation: every single character is itself a uniform block, so the prefix of length k can always be split into k blocks of one character each. For instance "aabb" also splits as one block ('a':2, 'b':2), but splitting into four single-character blocks gives a higher count.
Example 2
Input: s = "abc"
Output: [1, 2, 3]
Example 3
Input: s = "aaaa"
Output: [1, 2, 3, 4]
Note on a trickier variant
If the problem instead asks for the minimum number of uniform blocks (the harder, more interesting version), the answer for "aabbcc" would be [1, 1, 2, 1, 2, 1]. The DP below adapts to that variant with a single word change; think about where.
Edge cases to consider
- A single character is always a valid uniform block.
- A string of all identical characters: every substring is a valid block.
- Prefixes that genuinely cannot be partitioned (impossible under the standard definition above, but possible under stricter variants).
Hints
Hint 1
A single character always forms a valid uniform block on its own, which means any prefix of length k can be split into k such blocks. Before optimizing, make sure you understand what the true maximum looks like.
Hint 2
Model this as a 1-D DP: dp[i] = max blocks for the prefix of length i. For each end position i, sweep a left boundary j from i down to 0, growing the candidate last block s[j..i] one character at a time. You only need O(1) work per step if you maintain running counts incrementally.
Hint 3
To test whether s[j..i] is a uniform block in O(1), track the maximum character frequency (maxf) and the number of distinct characters (distinct) as you extend the block leftward. The block is uniform if and only if maxf × distinct == length of the block.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Clarify the contract first
A single character trivially satisfies the uniform-block rule: one distinct character, frequency 1. So for any prefix of length k, splitting into k individual characters is always valid, and no partition can have more than k non-empty pieces. The maximum is always k, giving list(range(1, n+1)) as a closed-form answer under the standard definition.
If that is all there is to it, say so in an interview. Then immediately offer the more interesting variant — minimum uniform blocks — because that is almost certainly what the interviewer intended, and it is where the real algorithmic work lives. The DP below solves the maximum version and flips to the minimum version by swapping max for min.
Core DP
Define dp[k] as the maximum number of uniform blocks that partition the prefix of length k. Set dp[0] = 0 (empty prefix, zero blocks) and everything else to negative infinity (unreachable).
For each end index i (0-indexed), consider every possible last block s[j..i] where j runs from i down to 0. If that block is uniform and dp[j] is reachable, then dp[i+1] can be updated to max(dp[i+1], dp[j] + 1).
The result at position i is dp[i+1] (or 0 if still unreachable).
O(1) validity check per step
Instead of rescanning the block every time j moves left, maintain three values incrementally:
cnt[c]— count of each character in the current blockdistinct— number of characters with a nonzero countmaxf— the largest count seen
A block of length L is uniform if and only if maxf * distinct == L. Here is why: the counts must sum to L, and each count is at most maxf. The only way the product equals the sum is if every count equals maxf exactly. This test is O(1) and replaces what would otherwise be an O(26) or O(L) scan.
maxf only ever increases as the block grows leftward, so it never needs to be recomputed from scratch.
Complexity
- Time: O(n²) — about n²/2
(j, i)pairs, each with O(1) work. Forn = 2000that is roughly 2 million steps. - Space: O(n) for
dp, O(26) forcnt.
The trivial closed-form answer is O(n) time, but the DP is what an interviewer is testing, and it generalises to the minimum variant and to constrained versions (e.g., blocks must have at least 2 distinct characters).
Python solution
from typing import List
def max_uniform_splits(s: str) -> List[int]:
n = len(s)
NEG = float("-inf")
# dp[k] = max uniform blocks for prefix of length k; -inf means unreachable
dp = [NEG] * (n + 1)
dp[0] = 0
for i in range(n):
cnt = [0] * 26
distinct = 0
maxf = 0
# Grow the last block s[j..i] leftward from j = i to j = 0.
# Each step adds one character to the left of the current block.
for j in range(i, -1, -1):
c = ord(s[j]) - 97
if cnt[c] == 0:
distinct += 1
cnt[c] += 1
if cnt[c] > maxf:
maxf = cnt[c]
length = i - j + 1
# Uniform iff every present character shares frequency maxf.
# Equivalent to: maxf * distinct == length.
if maxf * distinct == length and dp[j] != NEG:
candidate = dp[j] + 1
if candidate > dp[i + 1]:
dp[i + 1] = candidate
return [dp[k] if dp[k] != NEG else 0 for k in range(1, n + 1)]
Minimum-blocks variant
Change two lines: initialise unreachable states with +inf instead of -inf, and replace candidate > dp[i+1] with candidate < dp[i+1]. Everything else stays identical. Under this variant, "aabbcc" produces [1, 1, 2, 1, 2, 1] because longer uniform blocks are preferred.
Common mistakes
- Forgetting the empty-prefix base case.
dp[0] = 0is the anchor; without it, no partition ever gets started. - Updating
maxfonly upward. Because the block grows (never shrinks) in the inner loop,maxfis non-decreasing. You never need to recompute it fromcnt. - Off-by-one on indices.
dp[j]covers the prefix of lengthj, so the block iss[j..i](inclusive), and the result goes intodp[i+1]. - Conflating max and min. State clearly which variant you are solving before writing the recurrence.
Follow-ups
What if each block must have at least K distinct characters?
Add if distinct < K: continue (or break if distinct only grows, which it does). The asymptotic bound stays O(n²), but many inner loops terminate early on low-diversity strings.
Can you precompute a 2-D validity table?
Yes — valid[j][i] needs O(n²) space (about 4 MB as a NumPy bool array for n = 2000). But the DP consumes each row exactly once, so the incremental approach above streams validity at O(n) space with no time penalty.
Why not just use a hash map instead of a fixed-size array? For 26 lowercase letters, the fixed-size array is faster and simpler. A hash map makes sense if the alphabet is large or unknown, but adds constant-factor overhead with no asymptotic benefit here.