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: 3
💡 Note: Need to make entire string palindromic. Change positions to match: "leeecode" → "leeeeeel" requires 3 changes minimum.

Constraints

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

Visualization

Tap to expand
Palindrome Partitioning III: s="abc", k=2abcOriginal StringPartition Here"a""bb"Cost: 0Cost: 1Optimal PartitionTotal Cost: 0 + 1 = 1Change 'c' to 'b' to make "bc" → "bb" palindromic
Understanding the Visualization
1
Input
String "abc" with k=2 parts needed
2
Process
Find optimal way to partition and make palindromes
3
Output
Minimum 1 change needed
Key Takeaway
🎯 Key Insight: Precompute all substring palindrome costs, then use DP to find optimal k-way partition
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