Palindrome Partitioning IV - Problem

Given a string s, you need to determine if it's possible to split the string into exactly three non-empty palindromic substrings.

A palindrome is a string that reads the same forwards and backwards, like "racecar" or "aba".

Goal: Return true if the string can be partitioned into exactly 3 palindromic parts, false otherwise.

Example: For string "abccba", we can split it as "a" + "bccb" + "a" - all three parts are palindromes, so return true.

Challenge: You must find exactly three parts - no more, no less!

Input & Output

example_1.py โ€” Basic Valid Partition
$ Input: "abcbdd"
โ€บ Output: true
๐Ÿ’ก Note: We can split it as "a" + "bcb" + "dd". All three parts are palindromes: "a" is a palindrome, "bcb" is a palindrome, and "dd" is a palindrome.
example_2.py โ€” No Valid Partition
$ Input: "bcbddxy"
โ€บ Output: false
๐Ÿ’ก Note: No matter how we split this string into exactly three parts, at least one part will not be a palindrome. For example, "b" + "cb" + "ddxy" has "cb" and "ddxy" as non-palindromes.
example_3.py โ€” Edge Case Minimum Length
$ Input: "aaa"
โ€บ Output: true
๐Ÿ’ก Note: We can split it as "a" + "a" + "a". Each single character is a palindrome, so this is a valid partition into three palindromic substrings.

Constraints

  • 3 โ‰ค s.length โ‰ค 2000
  • s consists of only lowercase English letters
  • Must partition into exactly three non-empty parts

Visualization

Tap to expand
๐Ÿฏ a b c c b a ๐ŸฏChef's Ingredient ListCourse 1Course 2Course 3"a""bccb""a"โœ“ Balancedโœ“ Balancedโœ“ Balanced๐Ÿ“š Recipe Book (DP Table)"a" โ†’ Balanced โœ“"bccb" โ†’ Balanced โœ“"abccba" โ†’ Balanced โœ“๐ŸŽ‰ Perfect! All three courses are balanced โ†’ Return true
Understanding the Visualization
1
Build Recipe Book
First, create a reference book noting which ingredient combinations are 'balanced'
2
Try Cut Positions
Systematically try different positions to make the first and second cuts
3
Check Balance
For each partition attempt, quickly look up if all three courses are balanced
4
Success or Failure
Return true if any valid three-course arrangement is found
Key Takeaway
๐ŸŽฏ Key Insight: By preprocessing which substrings are palindromes, we avoid redundant checks and achieve optimal O(nยฒ) time complexity while trying all possible three-way partitions.
Asked in
Google 42 Amazon 38 Meta 25 Microsoft 18
28.5K Views
Medium-High Frequency
~18 min Avg. Time
892 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