Problem solution · Python

Minimum Changes to Make K Semi-palindromes

Minimum Changes to Make K Semi-palindromes: a Python solution using dynamic programming. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Dynamic programming
Source
walkccc LeetCode Solutions
Length
49 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Dynamic programming

For Minimum Changes to Make K Semi-palindromes, the implementation records answers for smaller states and reuses them to build the requested result without repeating work.

  1. Define precisely what one DP state represents.
  2. Establish the base cases before transitions are evaluated.
  3. Process states in dependency order and combine only already-known values.

Code notes

  • 49 lines of Python from the credited upstream file 2911.py.
  • The implementation visibly relies on sequence storage, cached states.
  • No explicit loop blocks detected.

Complexity

Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeMinimum Changes to Make K Semi-palindromes · PythonPython
Use this to learn the idea, then write your own version.
class Solution:  def minimumChanges(self, s: str, k: int) -> int:    n = len(s)    # factors[i] := factors of i    factors = self._getFactors(n)    # cost[i][j] := changes to make s[i..j] a semi-palindrome    cost = self._getCost(s, n, factors)    # dp[i][j] := the minimum changes to split s[i:] into j valid parts    dp = [[n] * (k + 1) for _ in range(n + 1)]     dp[n][0] = 0     for i in range(n - 1, -1, -1):      for j in range(1, k + 1):        for l in range(i + 1, n):          dp[i][j] = min(dp[i][j], dp[l + 1][j - 1] + cost[i][l])     return dp[0][k]   def _getFactors(self, n: int) -> list[list[int]]:    factors = [[1] for _ in range(n + 1)]    for d in range(2, n):      for i in range(d * 2, n + 1, d):        factors[i].append(d)    return factors   def _getCost(self, s: str, n: int, factors: list[list[int]]) -> list[list[int]]:    cost = [[0] * n for _ in range(n)]    for i, j in itertools.combinations(range(n), 2):      length = j - i + 1      minCost = length      for d in factors[length]:        minCost = min(minCost, self._getCostD(s, i, j, d))      cost[i][j] = minCost    return cost   def _getCostD(self, s: str, i: int, j: int, d: int) -> int:    """Returns the cost to make s[i..j] a semi-palindrome of `d`."""    cost = 0    for offset in range(d):      l = i + offset      r = j - d + 1 + offset      while l < r:        if s[l] != s[r]:          cost += 1        l += d        r -= d    return cost 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗