Description
Minimum Changes to Make K Semi-palindromes
HardGiven 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.
A semi-palindrome is a special type of string that can be divided into palindromes based on a repeating pattern. To check if a string is a semi-palindrome:
- Choose a positive divisor
dof the string's length.dcan range from1up to, but not including, the string's length. For a string of length1, it does not have a valid divisor as per this definition, since the only divisor is its length, which is not allowed. - For a given divisor
d, divide the string into groups where each group contains characters from the string that follow a repeating pattern of lengthd. Specifically, the first group consists of characters at positions1,1 + d,1 + 2d, and so on; the second group includes characters at positions2,2 + d,2 + 2d, etc. - The string is considered a semi-palindrome if each of these groups forms a palindrome.
Consider the string "abcabc":
- The length of
"abcabc"is6. Valid divisors are1,2, and3. - For
d = 1: The entire string"abcabc"forms one group. Not a palindrome. - For
d = 2:- Group 1 (positions
1, 3, 5):"acb" - Group 2 (positions
2, 4, 6):"bac" - Neither group forms a palindrome.
- Group 1 (positions
- For
d = 3:- Group 1 (positions
1, 4):"aa" - Group 2 (positions
2, 5):"bb" - Group 3 (positions
3, 6):"cc" - All groups form palindromes. Therefore,
"abcabc"is a semi-palindrome.
- Group 1 (positions
Example 1:
Input: s = "abcac", k = 2
Output: 1
Explanation: Divide s into "ab" and "cac". "cac" is already semi-palindrome. Change "ab" to "aa", it becomes semi-palindrome with d = 1.
Example 2:
Input: s = "abcdef", k = 2
Output: 2
Explanation: Divide s into substrings "abc" and "def". Each needs one change to become semi-palindrome.
Example 3:
Input: s = "aabbaa", k = 3
Output: 0
Explanation: Divide s into substrings "aa", "bb" and "aa". All are already semi-palindromes.
Constraints:
2 <= s.length <= 2001 <= k <= s.length / 2scontains only lowercase English letters.
Solutions
This function splits the string s into exactly k pieces (each at least 2 characters long) so that the total number of letter changes needed to turn every piece into a semi-palindrome is as small as possible. A semi-palindrome is a string that, for some divisor d of its length, reads the same forwards and backwards when you only look at every d-th character starting from each offset. The code works in three stages. First, it precomputes for every possible length the list of valid d values (divisors), so it doesn't recompute them repeatedly. Second, it builds a cost table where cost[start][end] is the minimum number of mismatched character pairs across all valid d for the substring s[start..end]; for each d it walks inward from both ends in steps of d and counts positions where s[l] !== s[r]. Third, a memoized recursive function dfs(start, remaining) chooses where to end the current piece: it tries every end that still leaves enough characters for the remaining pieces, adds cost[start][end] to the best result of the rest, and caches the answer in memo so overlapping subproblems are solved only once. The final answer is dfs(0, k), the cheapest way to cut the whole string into k semi-palindromes.
/** By ChatGPT */
var minimumChanges = function(s, k) {
const n = s.length;
// Valid proper divisors for every length
const divisors = Array.from(
{ length: n + 1 }, () => []
);
for (let d = 1; d <= n / 2; d++) {
for (let len = d * 2; len <= n; len += d) {
divisors[len].push(d);
}
}
// cost[i][j] = minimum changes to make
// s[i...j] a semi-palindrome
const cost = Array.from(
{ length: n }, () => Array(n).fill(Infinity)
);
for (let start = 0; start < n; start++) {
for (let end = start + 1; end < n; end++) {
const len = end - start + 1;
for (const d of divisors[len]) {
let changes = 0;
for (let offset = 0; offset < d; offset++) {
let l = start + offset;
let r = end - d + 1 + offset;
while (l < r) {
if (s[l] !== s[r]) changes++;
l += d;
r -= d;
}
}
cost[start][end] = Math.min(
cost[start][end],
changes
);
}
}
}
// Memoized partition DP
const memo = Array.from(
{ length: n }, () => Array(k + 1)
);
const dfs = (start, remaining) => {
if (remaining === 0) {
return start === n ? 0 : Infinity;
}
// Need at least 2 characters per remaining part
if (n - start < remaining * 2) {
return Infinity;
}
if (memo[start][remaining] !== undefined) {
return memo[start][remaining];
}
let best = Infinity;
// Current part must have >= 2 characters.
// Leave >= 2 for each remaining part.
const maxEnd = n - 2 * (remaining - 1) - 1;
for (let end = start + 1; end <= maxEnd; end++) {
const total =
cost[start][end] +
dfs(end + 1, remaining - 1);
best = Math.min(best, total);
}
return memo[start][remaining] = best;
};
return dfs(0, k);
};