Palindrome Partitioning III - Problem
You're given a string s containing lowercase letters and an integer k. Your mission is to transform this string into exactly k palindromic substrings with the minimum number of character changes possible.

Here's what you need to do:
1. Change some characters of s to other lowercase English letters
2. Divide the modified string into exactly k non-empty, non-overlapping substrings
3. Ensure each substring is a palindrome

Your goal is to find the minimum number of character changes needed to achieve this partitioning. This is a classic dynamic programming problem that combines string manipulation with optimization techniques.

Example: For string "abc" and k=2, you could change 'b' to 'a' to get "aac", then partition it as ["aa", "c"] - requiring only 1 change!

Input & Output

example_1.py โ€” Basic Case
$ Input: s = "abc", k = 2
โ€บ Output: 1
๐Ÿ’ก Note: We can change 'b' to 'a' to get "aac", then partition as ["aa", "c"]. Both "aa" and "c" are palindromes, and we only needed 1 character change.
example_2.py โ€” No Changes Needed
$ Input: s = "aabbc", k = 3
โ€บ Output: 0
๐Ÿ’ก Note: We can partition the string as ["aa", "bb", "c"] without any changes. All three parts are already palindromes.
example_3.py โ€” Multiple Changes
$ Input: s = "leetcode", k = 8
โ€บ Output: 0
๐Ÿ’ก Note: Since k equals the string length, each character forms its own part: ["l","e","e","t","c","o","d","e"]. Single characters are always palindromes, so no changes needed.

Constraints

  • 1 โ‰ค k โ‰ค s.length โ‰ค 100
  • s contains only lowercase English letters
  • k โ‰ค number of characters in s
  • Each partition must be non-empty

Visualization

Tap to expand
Palindrome Partitioning III - Complete SolutionInput: s="abc", k=2Step 1: Pre-compute Palindrome Costs"a"โ†’0"ab"โ†’1"abc"โ†’1Step 2: DP State Transitionsdp[1][1]=0dp[2][2]=1dp[3][2]=1dp[3][2] = min(dp[1][1] + cost(1,2), dp[2][1] + cost(2,2))dp[3][2] = min(0 + 1, 1 + 0) = 1Step 3: Optimal Partitioning Foundaโ†’abโ†’acResult: "aa" | "c" (1 change needed)
Understanding the Visualization
1
Pre-compute Costs
Calculate the cost to make every possible substring palindromic
2
Define DP State
dp[i][j] = minimum cost to partition first i characters into j parts
3
State Transition
For each state, try all possible positions for the last partition
4
Build Solution
Use memoization to avoid recalculating the same subproblems
Key Takeaway
๐ŸŽฏ Key Insight: Pre-computing palindrome costs enables efficient DP where we try all possible last partitions and choose the minimum cost path. The time complexity is O(nยฒk) with O(nยฒ) space.
Asked in
Google 32 Amazon 28 Microsoft 15 Meta 12
42.3K Views
Medium Frequency
~25 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen