Palindrome Partitioning IV — LeetCode 1745 Python Solution

HardStringDynamic Programming
Problem
#1745
Reading time
2 min

The problem

Given a string s, return true if it is possible to split the string s into three non-empty palindromic substrings. Otherwise, return false.​​​​​ A string is said to be palindrome if it the same string when reversed.

Example

Input
s = "abcbdd"
Output
true
Explanation
"abcbdd" = "a" + "bcb" + "dd", and all three substrings are palindromes.

Python solution

Python
class Solution:
    def checkPartitioning(self, s: str) -> bool:
        n = len(s)
        f = [[True] * n for _ in range(n)]
        for i in range(n - 1, -1, -1):
            for j in range(i + 1, n):
                f[i][j] = s[i] == s[j] and (i + 1 == j or f[i + 1][j - 1])
        for i in range(n - 2):
            for j in range(i + 1, n - 1):
                if f[0][i] and f[i + 1][j] and f[j + 1][-1]:
                    return True
        return False

Complexity

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1745. Palindrome Partitioning IV is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1745. Palindrome Partitioning IV?
LeetCode 1745. Palindrome Partitioning IV is rated Hard on LeetCode.
What topics does LeetCode 1745. Palindrome Partitioning IV cover?
LeetCode 1745. Palindrome Partitioning IV is tagged String and Dynamic Programming 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