Leetcode #2911: Minimum Changes to Make K Semi-palindromes
In this guide, we solve Leetcode #2911 Minimum Changes to Make K Semi-palindromes in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Given a string s and an integer k, partition s into k substrings such that the letter changes needed to make each substring a semi-palindrome are minimized. Return the minimum number of letter changes required.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Two Pointers, String, Dynamic Programming
Intuition
The constraints hint that we can reason about two ends of the data at once, which is perfect for a two-pointer scan.
Moving one pointer at a time keeps the invariant intact and avoids nested loops.
Approach
Place pointers at the left and right ends and move them based on the comparison or target condition.
This yields a clean linear pass after any required sorting.
Steps:
- Set left and right pointers.
- Move a pointer based on the condition.
- Update the best answer while scanning.
Python Solution
class Solution:
def minimumChanges(self, s: str, k: int) -> int:
n = len(s)
g = [[inf] * (n + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(i, n + 1):
m = j - i + 1
for d in range(1, m):
if m % d == 0:
cnt = 0
for l in range(m):
r = (m // d - 1 - l // d) * d + l % d
if l >= r:
break
if s[i - 1 + l] != s[i - 1 + r]:
cnt += 1
g[i][j] = min(g[i][j], cnt)
f = [[inf] * (k + 1) for _ in range(n + 1)]
f[0][0] = 0
for i in range(1, n + 1):
for j in range(1, k + 1):
for h in range(i - 1):
f[i][j] = min(f[i][j], f[h][j - 1] + g[h + 1][i])
return f[n][k]
Complexity
The time complexity is O(n) (after optional sort O(n log n)). The space complexity is O(1).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.