KatInterview

Maximum Valid-Partition Block Count for Every Prefix

Dynamic ProgrammingModel answer
MediumModel answerDynamic Programmingdynamic programmingstringsfrequency counting

Last 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) <= 2000
  • s consists 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.