Anirudh Sharma
BlogDSASkillsPortfolio
© Anirudh SharmaBlogDSASkillsGitHubEmail
← All problems

Problem of the day18 Nov 2026·Hard

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
Solve on LeetCode (#2911) ↗

On this page

  1. The problem
  2. The slow way
  3. The key idea
  4. See it step by step
  5. The algorithm
  6. Dry run
  7. Code
  8. Complexity
  9. Common mistakes
  10. Practice next

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

  1. 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.

  2. Price one piece for one d

    Fix a piece s[i..j] and a divisor d. Group g holds the letters at i + 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.

  3. Take the cheapest d, for every piece

    A piece may use any valid d, so its cost is the minimum over all d that divide its length (excluding the length itself). Work this out for every i <= j up front and store it in cost[i][j]. A piece of length 1 gets no cost at all: it can never be a semi-palindrome.

  4. Choose the cuts with DP

    Let dp[i][p] be the fewest changes to cut the suffix s[i..] into exactly p pieces. The first piece is s[i..x] for some x, 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 from dp[n][0] = 0 (nothing left, nothing to cut). The answer is dp[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.

Try:

Click a first and a last letter to choose a piece. Letters with the same colour are in the same group.

Piece "abcac", length 5. Divisors:
Group 1abcaca ↔ c ✗ +1b ↔ a ✗ +12
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

  1. For every length L, list the divisors d with L % d == 0 and d < L.
  2. For every piece s[i..j] with at least 2 letters, and every divisor d of its length: walk each group g from both ends and count the pairs that differ. cost[i][j] is the smallest count over all d.
  3. Set dp[n][0] = 0 and everything else to infinity.
  4. For p = 1..k, for each start i (from right to left), try every first piece s[i..x]: dp[i][p] = min(dp[i][p], cost[i][x] + dp[x + 1][p - 1]).
  5. Return dp[0][k].

Dry run

s = "abcac", k = 2

CellMeansFirst piece + restBest
dp[5][0]nothing left, 0 pieces–0
dp[3][1]"ac" as 1 piece"ac" costs 1 (d = 1) + dp[5][0] = 0 → 11
dp[2][1]"cac" as 1 piece"cac" costs 0 (d = 1) + dp[5][0] = 0 → 00
dp[0][2]"abcac" as 2 pieces"ab" 1 + dp[2][1] 0 → 1 · "abc" 1 + dp[3][1] 1 → 21

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

TimeO(n³ · D + k · n²)
SpaceO(n² + n · k)

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 it 0, you will cut too finely and get answers that are too small.
  • Letting d equal the length. With d = L every group has one letter and every string would count as "semi" for free. d must be strictly smaller than L.
  • Stopping at the first d that looks good. Different divisors give different costs; "abcabc" costs 2 with d = 1 but 0 with d = 3. Always take the minimum over all of them.
  • Indexing groups from the start of the whole string. Group g of the piece s[i..j] starts at i + g, not at g. 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 k times, which is far too slow for n = 200. Build cost[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.

Practice next

  • 1278. Palindrome Partitioning III ↗The same cost table plus cut DP, with plain palindromes. Solve it first.
  • 132. Palindrome Partitioning II ↗Fewest cuts so every piece is a palindrome, with no changes allowed.
  • 410. Split Array Largest Sum ↗Same "first piece + best split of the rest" DP into k parts, with a different cost.
  • 1335. Minimum Difficulty of a Job Schedule ↗Cut a list into exactly d days; each day's cost is its hardest job.
← All problemsSubmit on LeetCode ↗