Minimum Substring Partition of Equal Character Frequency - Problem

Given a string s, you need to partition it into one or more balanced substrings.

For example, if s == "ababcc" then ("abab", "c", "c"), ("ab", "abc", "c"), and ("ababcc") are all valid partitions, but ("a", "bab", "cc"), ("aba", "bc", "c"), and ("ab", "abcc") are not valid because they contain unbalanced substrings.

Return the minimum number of substrings that you can partition s into.

Note: A balanced string is a string where each character in the string occurs the same number of times.

Input & Output

Example 1 — Basic Case
$ Input: s = "ababcc"
Output: 3
💡 Note: We can partition into ("abab", "c", "c"). "abab" has a:2, b:2 (balanced), each "c" has c:1 (balanced). Total: 3 partitions.
Example 2 — Single Character
$ Input: s = "aaaa"
Output: 1
💡 Note: The entire string "aaaa" has a:4, so it's balanced. We need only 1 partition.
Example 3 — All Different Characters
$ Input: s = "abc"
Output: 3
💡 Note: Each character appears once, so "a", "b", "c" are each balanced. We need 3 partitions.

Constraints

  • 1 ≤ s.length ≤ 1000
  • s consists only of lowercase English letters

Visualization

Tap to expand
Minimum Substring Partition INPUT String s = "ababcc" a b a b c c 0 1 2 3 4 5 Balanced String: Each character appears same number of times "ab" OK: a=1, b=1 Valid Partitions: ("ab", "ab", "cc") ("abab", "c", "c") Invalid: ("a", "bab", "cc") "bab" not balanced ALGORITHM STEPS 1 Initialize DP Array dp[i] = min partitions for s[0..i] 2 Iterate Each Position For each end index i in string 3 Check All Substrings Try all j where s[j..i] balanced 4 Update Minimum dp[i] = min(dp[i], dp[j-1]+1) Greedy Trace: ab a:1 b:1 ab a:1 b:1 cc c:2 All 3 parts are balanced! Partitions = 3 FINAL RESULT Optimal Partition Found: "ab" "ab" "cc" Output: 3 Verification: Part 1: "ab" a=1, b=1 OK Part 2: "ab" a=1, b=1 OK Part 3: "cc" c=2 OK All parts balanced! Key Insight: The greedy approach works by finding the earliest position where we can make a valid balanced substring cut. A string is balanced when all character frequencies are equal. We use dynamic programming with frequency counting to find minimum partitions in O(n^2) time complexity. TutorialsPoint - Minimum Substring Partition of Equal Character Frequency | Greedy Approach
Asked in
Google 25 Amazon 18 Microsoft 15
23.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen