Longest Chunked Palindrome Decomposition - Problem
The Longest Chunked Palindrome Decomposition is a fascinating string manipulation challenge that tests your ability to find patterns and optimize substring matching.
Given a string
Requirements:
Your goal is to find the maximum possible value of k - meaning you want to create as many chunks as possible while maintaining the palindromic property.
Example: For
Given a string
text, your task is to split it into k substrings such that they form a chunked palindrome. A chunked palindrome means that the first chunk equals the last chunk, the second chunk equals the second-to-last chunk, and so on.Requirements:
- Each substring must be non-empty
- All substrings concatenated must equal the original
text - The
i-thsubstring must equal the(k-i+1)-thsubstring
Your goal is to find the maximum possible value of k - meaning you want to create as many chunks as possible while maintaining the palindromic property.
Example: For
"ghiabcdefhelloadamhelloabcdefghi", one optimal decomposition could be ["ghi", "abcdef", "hello", "adam", "hello", "abcdef", "ghi"] with k = 7. Input & Output
example_1.py โ Python
$
Input:
text = "ghiabcdefhelloadamhelloabcdefghi"
โบ
Output:
7
๐ก Note:
One optimal decomposition is ["ghi", "abcdef", "hello", "adam", "hello", "abcdef", "ghi"] where pairs (1,7), (2,6), (3,5) match and middle element is "adam".
example_2.py โ Python
$
Input:
text = "merchant"
โบ
Output:
1
๐ก Note:
No way to split "merchant" into matching chunks, so the entire string forms one chunk.
example_3.py โ Python
$
Input:
text = "antaprezatepzapreanta"
โบ
Output:
11
๐ก Note:
Optimal decomposition: ["a", "n", "t", "a", "p", "re", "z", "re", "p", "a", "t", "a", "n", "t", "a"] but actually ["a", "nt", "a", "pre", "za", "t", "e", "p", "za", "pre", "a", "nt", "a"] gives 11 chunks.
Visualization
Tap to expand
Understanding the Visualization
1
Identify Matching Ends
Look for the shortest possible matching prefix and suffix
2
Peel Off Matches
Remove matched chunks and count them as 2 chunks
3
Repeat on Remainder
Apply the same process recursively to the remaining middle portion
4
Handle Final Chunk
When no more matches are possible, the remainder forms one final chunk
Key Takeaway
๐ฏ Key Insight: The greedy strategy works because shorter matching chunks always allow for more total chunks than longer ones, leading to the optimal decomposition.
Time & Space Complexity
Time Complexity
O(nยฒ)
In worst case, we might compare O(n) different lengths, each taking O(n) time for string comparison
โ Quadratic Growth
Space Complexity
O(1)
Only using a few variables for pointers and counters, no additional data structures
โ Linear Space
Constraints
- 1 โค text.length โค 1000
- text consists only of lowercase English letters
- The string is guaranteed to be non-empty
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code