Palindrome Partitioning III - Problem

You are given a string s containing lowercase letters and an integer k.

You need to:

  1. First, change some characters of s to other lowercase English letters.
  2. Then divide s into k non-empty disjoint substrings such that each substring is a palindrome.

Return the minimal number of characters that you need to change to divide the string.

Input & Output

Example 1 — Basic Case
$ Input: s = "abc", k = 2
Output: 1
💡 Note: Change one character to create palindromes: "a" | "bb" (change 'c' to 'b') or "aa" | "c" (change 'b' to 'a'). Minimum cost is 1.
Example 2 — Already Palindromic
$ Input: s = "aabaa", k = 3
Output: 0
💡 Note: Can partition as "a" | "aba" | "a" with no changes needed since each part is already palindromic.
Example 3 — Single Part
$ Input: s = "leetcode", k = 1
Output: 4
💡 Note: Need to make entire string palindromic. Comparing from both ends: l↔e(1 change), e↔d(1 change), e↔o(1 change), t↔c(1 change). Total: 4 changes minimum.

Constraints

  • 1 ≤ k ≤ s.length ≤ 100
  • s consists of lowercase English letters only

Visualization

Tap to expand
Palindrome Partitioning III INPUT String s: 'a' 'b' 'c' 0 1 2 Partitions k: 2 Goal: Split into k palindrome substrings with min changes s = "abc", k = 2 ALGORITHM STEPS 1 Compute cost[i][j] Min changes to make s[i..j] palindrome 2 Define DP state dp[i][j] = min changes for s[0..i] with j parts 3 DP Transition dp[i][j] = min over m: dp[m][j-1] + cost[m+1][i] 4 Return dp[n-1][k] Answer for full string with k partitions Cost Table Example: a:0 b:0 c:0 ab:1 FINAL RESULT Optimal Partition: 'a' Palindrome 0 changes "bc" "bb" Palindrome 1 change | Total Changes: 1 OK - Minimum achieved! "a" | "bb" (was "bc") 2 palindromic substrings Output: 1 Key Insight: Use 2D DP where dp[i][j] represents minimum changes to partition s[0..i] into j palindromic substrings. Precompute cost[i][j] = min changes to make substring s[i..j] a palindrome by comparing characters from both ends. Time: O(n^2 * k), Space: O(n^2) for cost table + O(n*k) for DP table. TutorialsPoint - Palindrome Partitioning III | Dynamic Programming Approach
Asked in
Google 15 Amazon 12 Microsoft 8
28.0K Views
Medium Frequency
~25 min Avg. Time
890 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