Palindrome Partitioning IV - 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 reads the same string when reversed.

Input & Output

Example 1 — Valid 3-Way Split
$ Input: s = "abcba"
Output: true
💡 Note: We can split "abcba" into "a" + "bcb" + "a". All three parts are palindromes: "a" is palindrome, "bcb" is palindrome, "a" is palindrome.
Example 2 — No Valid Split
$ Input: s = "abc"
Output: false
💡 Note: No matter how we split "abc" into 3 non-empty parts, we cannot make all parts palindromes. For example: "a" + "b" + "c" - all single chars are palindromes but this works. Wait, let me recalculate: "a"|"b"|"c" are all palindromes, so this should be true. Let me use a different example.
Example 2 — No Valid Split
$ Input: s = "abcd"
Output: false
💡 Note: No matter how we split "abcd" into 3 parts, at least one part won't be a palindrome. For instance: "a"|"b"|"cd" - "cd" is not palindrome, "a"|"bc"|"d" - "bc" is not palindrome.
Example 3 — Minimum Length
$ Input: s = "aaa"
Output: true
💡 Note: We can split "aaa" into "a" + "a" + "a". All three single character parts are palindromes.

Constraints

  • 3 ≤ s.length ≤ 2000
  • s consists of only lowercase English letters

Visualization

Tap to expand
Palindrome Partitioning IV INPUT String s = "abcba" a 0 b 1 c 2 b 3 a 4 Goal: Split into 3 palindromes Part 1 Part 2 Part 3 Each must be a palindrome Constraints: - 3 <= s.length <= 2000 - lowercase letters only ALGORITHM STEPS 1 Precompute Palindromes Build isPalin[i][j] table isPalin[i][j] True if s[i..j] is palindrome 2 Find First Split Point Check isPalin[0][i] 3 Find Second Split Check isPalin[i+1][j] 4 Verify Third Part Check isPalin[j+1][n-1] Two-Pass Approach: Pass 1: Build table O(n^2) Pass 2: Find splits O(n^2) FINAL RESULT Valid Partition Found: "a" Palindrome + "bcb" Palindrome + "a" Palindrome Verification: "a" == "a" [OK] "bcb" == "bcb" [OK] Output: true Split: i=0, j=3 s[0:0] + s[1:3] + s[4:4] All three are palindromes! Key Insight: The Two-Pass approach first precomputes all palindrome substrings in O(n^2) time using dynamic programming. Then it iterates through all possible split points (i, j) checking if s[0..i], s[i+1..j], and s[j+1..n-1] are all palindromes using the precomputed table. This gives O(n^2) time and O(n^2) space complexity. TutorialsPoint - Palindrome Partitioning IV | Optimized Two-Pass Approach
Asked in
Facebook 25 Google 20 Microsoft 15
32.0K Views
Medium Frequency
~25 min Avg. Time
850 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