Longest Chunked Palindrome Decomposition — LeetCode 1147 Python Solution

HardGreedyTwo PointersStringDynamic ProgrammingHash FunctionRolling Hash
Problem
#1147
Reading time
3 min

The problem

You are given a string text. You should split it to k substrings (subtext1, subtext2, ..., subtextk) such that: subtexti is a non-empty string.

Example

Input
text = "ghiabcdefhelloadamhelloabcdefghi"
Output
7
Explanation
We can split the string on "(ghi)(abcdef)(hello)(adam)(hello)(abcdef)(ghi)".

Python solution

Python
class Solution:
    def longestDecomposition(self, text: str) -> int:
        ans = 0
        i, j = 0, len(text) - 1
        while i <= j:
            k = 1
            ok = False
            while i + k - 1 < j - k + 1:
                if text[i : i + k] == text[j - k + 1 : j + 1]:
                    ans += 2
                    i += k
                    j -= k
                    ok = True
                    break
                k += 1
            if not ok:
                ans += 1
                break
        return ans

Complexity

MeasureComplexity
TimeO(n^2)
SpaceO(n) or O(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 1147. Longest Chunked Palindrome Decomposition is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1147. Longest Chunked Palindrome Decomposition?
LeetCode 1147. Longest Chunked Palindrome Decomposition is rated Hard on LeetCode.
What topics does LeetCode 1147. Longest Chunked Palindrome Decomposition cover?
LeetCode 1147. Longest Chunked Palindrome Decomposition is tagged Greedy, Two Pointers, String, Dynamic Programming, Hash Function and Rolling Hash on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview