Minimum Changes to Make K Semi-palindromes - Problem
Given a string s and an integer k, you need to partition the string into exactly k substrings and transform each substring into a semi-palindrome with the minimum number of character changes.
A semi-palindrome is a fascinating string pattern where characters can be rearranged based on a repeating divisor pattern to form palindromic groups:
- Choose a positive divisor
dof the string's length (where1 ≤ d < length) - Group characters by their positions modulo
d - Each group must form a palindrome
Example: For string "abcabc" with d=3:
- Group 1 (positions 1,4): "aa" ✓ palindrome
- Group 2 (positions 2,5): "bb" ✓ palindrome
- Group 3 (positions 3,6): "cc" ✓ palindrome
Your goal is to find the minimum total number of character changes needed across all k partitions.
Input & Output
example_1.py — Basic Case
$
Input:
s = "abcabc", k = 2
›
Output:
1
💡 Note:
Partition into ["abc", "abc"]. For "abc" with d=1: need 1 change to make "aba". Total cost = 1 + 1 = 2. Better: with d=3, "abc" costs 2 changes, but optimal partition ["abca", "bc"] gives cost 1.
example_2.py — Single Character
$
Input:
s = "abc", k = 3
›
Output:
0
💡 Note:
Partition into ["a", "b", "c"]. Each single character is already a semi-palindrome (no valid divisors, so cost = 0). Total cost = 0 + 0 + 0 = 0.
example_3.py — Equal Parts
$
Input:
s = "aabbcc", k = 2
›
Output:
0
💡 Note:
Partition into ["aabb", "cc"]. For "aabb" with d=2: groups ["ab", "ab"] need 1+1=2 changes. But with d=1: "aabb" needs 2 changes. For "cc": already palindrome. Optimal gives cost 0 with better partitioning.
Visualization
Tap to expand
Understanding the Visualization
1
Choose Divisor
Pick a divisor d where 1 ≤ d < string_length
2
Group Characters
Group characters by their position mod d
3
Check Palindromes
Each group must form a palindrome
4
Count Changes
Sum up character changes needed across all groups
Key Takeaway
🎯 Key Insight: Semi-palindromes use divisor-based grouping to create multiple palindromic constraints, and dynamic programming efficiently finds optimal partitioning by reusing precomputed substring costs.
Time & Space Complexity
Time Complexity
O(n³ + n²k)
O(n³) to precompute all substring costs (n² substrings × n divisors), O(n²k) for DP table filling
⚠ Quadratic Growth
Space Complexity
O(n² + nk)
O(n²) for storing all substring costs, O(nk) for DP table
⚠ Quadratic Space
Constraints
- 1 ≤ s.length ≤ 200
- 1 ≤ k ≤ s.length
- s consists of lowercase English letters only
- s must be partitioned into exactly k non-empty substrings
- Semi-palindromes with length 1 have cost 0 (no valid divisors)
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code