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: 1
💡 Note: No palindromic decomposition is possible for this string. No prefix matches any suffix, so the entire string forms one chunk.
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 Decomposition INPUT text = "ghiabcdefhelloadefghiabcdef" g h i a b c d e f h e l l o a d e f g h i a b c d e f Palindrome Structure: ghi abcdef hello adef ghiabc def Two pointers: left and right Match chunks greedily L --> prefix suffix <-- R Compare prefix == suffix Length: 27 characters ALGORITHM STEPS (Greedy Approach) 1 Initialize Pointers left=0, right=len-1 k=0 (chunk count) 2 Expand and Match Try increasing prefix length Compare with suffix 3 On Match Found k += 2 (both chunks) Move pointers inward 4 Handle Middle If remaining, k += 1 Return total k Greedy Matches: "ghi" == "def" X "ghia" == "cdef" X "ghiabcdef" OK "hello" (mid) OK Greedy: take first match found FINAL RESULT 7 Chunks Found: Chunk 1 "ghi" Chunk 2 "abcdef" Chunk 3 "hello" Chunk 4 "a" Chunk 5 "def" Chunk 6 "ghiabc" Chunk 7 "def" Palindrome Pattern: 1 2 3 4 3 2 1 1 == 7, 2 == 6, 3 == 5 4 is middle chunk Output: k = 7 Maximum chunks [OK] Valid palindrome decomposition achieved Key Insight: The greedy approach works because taking the smallest matching prefix/suffix pair at each step maximizes the number of chunks. If we find a match, we split immediately and recurse on the middle. Time Complexity: O(n^2) where n is string length. Each comparison may take O(n) time. TutorialsPoint - Longest Chunked Palindrome Decomposition | Greedy Approach
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