Split a String into Exactly Three Palindromes
OracleBackend Engineer · OnsiteLast updated
Tests string partitioning, palindrome verification, and algorithmic optimization using dynamic programming or two pointers.
Problem Statement
Given a string s, determine whether it is possible to split s into exactly three non-empty contiguous substrings, each of which is a palindrome, such that concatenating them in order reconstructs the original string s.
A string is a palindrome if it reads the same forwards and backwards.
Write a function that returns True if such a partition exists, and False otherwise.
Function Signature
def can_split_three_palindromes(s: str) -> bool:
pass
Input & Output Format
- Input: A single string
scontaining only lowercase English letters. - Output: A boolean value (
Trueif a valid 3-palindrome partition exists,Falseotherwise).
Constraints
3 <= len(s) <= 2000sconsists solely of lowercase English letters ('a'-'z').
Examples
Example 1
Input: s = "abacaba"
Output: True
Explanation: We can split the string into ["aba", "c", "aba"], all of which are palindromes.
Example 2
Input: s = "abcb"
Output: False
Explanation: The possible 3-part splits are:
- ["a", "b", "cb"] -> "cb" is not a palindrome.
- ["a", "bc", "b"] -> "bc" is not a palindrome.
- ["ab", "c", "b"] -> "ab" is not a palindrome.
None of the splits yield three palindromes.
Example 3
Input: s = "aaaa"
Output: True
Explanation: Splits such as ["a", "a", "aa"] or ["a", "aa", "a"] produce three valid palindromes.
Edge Cases to Consider
- Strings of minimum length (
len(s) == 3), where every individual character is naturally a palindrome of length 1. - Strings where all characters are identical.
- Cases where the first and third parts are valid palindromes, but the middle part is not.
Hints
Hint 1
Consider fixing two split positions i and j to divide the string into s[0:i], s[i:j], and s[j:n].
Hint 2
Precomputing whether any substring s[l:r] is a palindrome eliminates redundant checks during search.
Hint 3
A 2D boolean dynamic programming table or expanding around centers can build the palindrome lookup in O(n^2) time.
Follow-up questions
- How would you modify your solution to return the actual three substrings instead of just a boolean?
- Can you reduce the space complexity to O(n) or O(1) auxiliary space while preserving O(n^2) time complexity?
- How does the problem change if you are asked to find the minimum number of palindromic cuts needed to partition the entire string?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.