Longest Chunked Palindrome Decomposition - Problem

You are given a string text. You should split it to k substrings (subtext₁, subtext₂, ..., subtextₖ) such that:

  • subtextᵢ is a non-empty string.
  • The concatenation of all the substrings is equal to text (i.e., subtext₁ + subtext₂ + ... + subtextₖ == text).
  • subtextᵢ == subtextₖ₋ᵢ₊₁ for all valid values of i (i.e., 1 <= i <= k).

Return the largest possible value of k.

Input & Output

Example 1 — Palindromic Chunks
$ Input: text = "ghiabcdefhelloadefghiabcdef"
Output: 7
💡 Note: Split into: (ghi)(abcdef)(hello)(a)(def)(ghiabcdef) - wait, this doesn't work. Let me recalculate... Actually: (ghi)(abc)(def)(hello)(a)(def)(abc)(ghi) = 8 chunks, but let's verify the greedy approach gives the optimal split.
Example 2 — Single Character
$ Input: text = "aa"
Output: 2
💡 Note: Split into (a)(a) - two matching single character chunks
Example 3 — No Splits
$ Input: text = "abc"
Output: 1
💡 Note: No way to split into palindromic chunks, so the whole string is one chunk

Constraints

  • 1 ≤ text.length ≤ 1000
  • text consists of lowercase English letters only

Visualization

Tap to expand
Longest Chunked Palindrome DecompositionghiabcdefhelloadefghiabcdefSplit into palindromic chunks:ghiabcdefhelloadefabcghiMatching pairs: (ghi,ghi), (abc,abc), (def,def)Result: k = 8 chunks maximumGreedy approach: match shortest chunks first
Understanding the Visualization
1
Input String
Given string to split into palindromic chunks
2
Find Matches
Identify matching prefix-suffix pairs greedily
3
Count Chunks
Return maximum number of valid chunks
Key Takeaway
🎯 Key Insight: Greedily matching the shortest prefix-suffix pairs maximizes the total number of chunks
Asked in
Google 15 Facebook 8
12.0K Views
Medium Frequency
~25 min Avg. Time
450 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