Minimum Changes to Make K Semi-palindromes
Cut a string into k pieces so the fewest letters need changing to make every piece a semi-palindrome: price every piece once, then pick the cuts with DP.
- Partition DP
- Precomputation
- Palindromes
- Divisors & Number Theory
- Two Pointers
- Two Pointers
- String
- Dynamic Programming
The problem
You get a lowercase string s and a number k. Cut s into exactly k non-empty pieces. Then change as few letters as you can so that every piece is a semi-palindrome. Return that smallest number of changes.
A piece of length L is a semi-palindrome if you can pick some d with 1 <= d < L and L % d == 0, so that this works: deal the letters into d groups by position (letter 1 to group 1, letter 2 to group 2, …, letter d + 1 back to group 1), and every group reads the same backwards.
For example "abcabc" with d = 3 gives the groups "aa", "bb" and "cc", all palindromes, so it is a semi-palindrome. A single letter never is: its only divisor is its own length, which is not allowed.
Example 1
Input s = "abcac", k = 2
Output 1
Cut into "ab" and "cac". "cac" is already a palindrome (d = 1). Change "ab" to "aa": 1 change.
Example 2
Input s = "abcdef", k = 2
Output 2
Cut into "abc" and "def". Each needs one change, like "aba" and "ded".
Example 3
Input s = "aabbaa", k = 3
Output 0
"aa", "bb" and "aa" are already semi-palindromes.
Constraints: 2 <= s.length <= 200 · 1 <= k <= s.length / 2 · s has only lowercase English letters
The slow way
Try every way to place the k - 1 cuts, and for every piece try every d and count the changes. The number of ways to cut grows like C(n - 1, k - 1). For n = 200 and k = 100 that is about 10^58 ways, so this never finishes.
Time O(C(n, k) · n²)Space O(k)
The key idea
Split the problem in two
There are two separate questions: how much does one piece cost to fix, and where should the cuts go. The cost of a piece does not depend on how the rest of the string is cut, so answer the first question once for every piece, then use those answers for the second.
Price one piece for one d
Fix a piece
s[i..j]and a divisord. Groupgholds the letters ati + g, i + g + d, i + g + 2d, …. To make a group a palindrome, compare its first and last letter, then the second and second-to-last, and so on (two pointers walking inwards). Every pair that differs costs exactly one change: set one letter to match the other.Take the cheapest d, for every piece
A piece may use any valid
d, so its cost is the minimum over alldthat divide its length (excluding the length itself). Work this out for everyi <= jup front and store it incost[i][j]. A piece of length 1 gets no cost at all: it can never be a semi-palindrome.Choose the cuts with DP
Let
dp[i][p]be the fewest changes to cut the suffixs[i..]into exactlyppieces. The first piece iss[i..x]for somex, and the rest is the same problem one piece smaller:dp[i][p] = min over x of cost[i][x] + dp[x + 1][p - 1]. Start fromdp[n][0] = 0(nothing left, nothing to cut). The answer isdp[0][k].
See it step by step
Two parts. Price one piece: click a first and a last letter, then switch between divisors. Letters in the same group share a colour, and pairs that need a change are marked. Find the best cuts: press Next to fill the DP table one cell at a time and see which first piece wins. Try the presets or type your own string.
Click a first and a last letter to choose a piece. Letters with the same colour are in the same group.
- Changes with d = 1
- 2
- Cheapest d
- 1
- cost[0][4]
- 2
With d = 1 the whole piece "abcac" is one group, so it must be a plain palindrome. 2 pairs differ, so 2 changes.
The algorithm
- For every length
L, list the divisorsdwithL % d == 0andd < L. - For every piece
s[i..j]with at least 2 letters, and every divisordof its length: walk each groupgfrom both ends and count the pairs that differ.cost[i][j]is the smallest count over alld. - Set
dp[n][0] = 0and everything else to infinity. - For
p = 1..k, for each starti(from right to left), try every first pieces[i..x]:dp[i][p] = min(dp[i][p], cost[i][x] + dp[x + 1][p - 1]). - Return
dp[0][k].
Dry run
s = "abcac", k = 2
| Cell | Means | First piece + rest | Best |
|---|---|---|---|
| dp[5][0] | nothing left, 0 pieces | – | 0 |
| dp[3][1] | "ac" as 1 piece | "ac" costs 1 (d = 1) + dp[5][0] = 0 → 1 | 1 |
| dp[2][1] | "cac" as 1 piece | "cac" costs 0 (d = 1) + dp[5][0] = 0 → 0 | 0 |
| dp[0][2] | "abcac" as 2 pieces | "ab" 1 + dp[2][1] 0 → 1 · "abc" 1 + dp[3][1] 1 → 2 | 1 |
The answer is dp[0][2] = 1: cut into "ab" + "cac". "abca" + "c" is never tried, because a single letter can not be a semi-palindrome.
Code
Same logic in all three languages. The comments match the steps above.
class Solution:
def minimumChanges(self, s: str, k: int) -> int:
n = len(s)
INF = 10**9
# divisors[L] = every d that splits a length-L piece: L % d == 0 and d < L
divisors = [[] for _ in range(n + 1)]
for d in range(1, n + 1):
for L in range(2 * d, n + 1, d):
divisors[L].append(d)
# cost[i][j] = fewest changes to make s[i..j] a semi-palindrome
cost = [[INF] * n for _ in range(n)]
for i in range(n):
for j in range(i + 1, n): # length >= 2: one letter is never semi
L = j - i + 1
for d in divisors[L]:
changes = 0
# Group g holds i+g, i+g+d, ... and ends at j-d+1+g.
for g in range(d):
lo, hi = i + g, j - d + 1 + g
# Walk in from both ends, like a normal palindrome check.
while lo < hi:
if s[lo] != s[hi]:
changes += 1
lo += d
hi -= d
cost[i][j] = min(cost[i][j], changes)
# dp[i][p] = fewest changes to cut s[i:] into exactly p pieces
dp = [[INF] * (k + 1) for _ in range(n + 1)]
dp[n][0] = 0 # nothing left and no pieces to make: free
for p in range(1, k + 1):
# Each piece needs at least 2 letters, so s[i:] needs 2 * p of them.
for i in range(n - 2 * p, -1, -1):
for x in range(i + 1, n): # first piece is s[i..x]
rest = dp[x + 1][p - 1]
if rest < INF:
dp[i][p] = min(dp[i][p], cost[i][x] + rest)
return dp[0][k]Complexity
Pricing one piece of length L for one divisor d takes about L / 2 comparisons. There are O(n²) pieces and at most D divisors each (D = 17, reached at length 180), so the cost table takes O(n³ · D), a few million steps for n = 200. The DP has n · k cells and tries up to n first pieces in each. The two tables use O(n²) and O(n · k) memory.
Common mistakes
- Allowing pieces of length 1. A single letter has no valid
d, so it can never be a semi-palindrome. If your cost table gives it0, you will cut too finely and get answers that are too small. - Letting
dequal the length. Withd = Levery group has one letter and every string would count as "semi" for free.dmust be strictly smaller thanL. - Stopping at the first
dthat looks good. Different divisors give different costs;"abcabc"costs 2 withd = 1but 0 withd = 3. Always take the minimum over all of them. - Indexing groups from the start of the whole string. Group
gof the pieces[i..j]starts ati + g, not atg. The pattern restarts at every piece. - Pricing pieces inside the DP loop. Recomputing the cost each time the DP looks at a piece repeats the same work about
ktimes, which is far too slow forn = 200. Buildcost[i][j]once first. - Cutting greedily. Taking the cheapest first piece can leave an expensive rest. Only the DP, which tries every first piece, is safe.