Taro Logo

Palindrome Partitioning IV

Hard
Asked by:
Tata Consultancy Services
0 views
Topics:
StringsDynamic Programming

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 1:

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

Example 2:

Input: s = "bcbddxy"
Output: false
Explanation: s cannot be split into 3 palindromes.

Constraints:

  • 3 <= s.length <= 2000
  • s​​​​​​ consists only of lowercase English letters.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum length of the string `s` that we might receive as input?
  2. Does the string contain only lowercase English letters, or should I account for uppercase letters, numbers, or special characters?
  3. Are the three partitioned substrings strictly required to be non-empty?
  4. If there are multiple ways to partition the string into three palindromes, do we just need to return a boolean for whether *any* valid partition exists?
  5. Can the input string be shorter than 3 characters, and how should that be handled?

Brute Force Solution

Approach

The problem asks whether a given string can be divided into three non-empty palindromic substrings. We can solve this by precomputing the palindrome status for every possible substring using dynamic programming. After building the table, we iterate through all possible split locations to check if the three resulting parts are all palindromes.

Here's how the algorithm would work step-by-step:

  1. Determine the length of the input string and initialize a 2D boolean array to store palindrome information for every substring.
  2. Iterate through the string to fill the table by checking character matches at both ends and the palindrome status of the inner substring.
  3. Iterate over the first split point to ensure the first substring forms a valid palindrome.
  4. Iterate over the second split point to verify that both the middle and the third substrings are also valid palindromes.
  5. Return true immediately if a valid three-way partition is found; otherwise, return false after testing all combinations.

Code Implementation

def check_partitioning(target_string):
    string_length = len(target_string)
    # Initialize a 2D boolean table to store whether substrings are palindromes.
    is_palindrome = [[False] * string_length for _ in range(string_length)]
    
    # Populate the palindrome table for all substring lengths.
    for end_index in range(string_length):
        for start_index in range(end_index + 1):
            if target_string[start_index] == target_string[end_index]:
                if end_index - start_index <= 2 or is_palindrome[start_index + 1][end_index - 1]:
                    is_palindrome[start_index][end_index] = True
                    
    # Check all possible split points into three non-empty substrings.
    for first_cut in range(string_length - 2):
        if is_palindrome[0][first_cut]:
            for second_cut in range(first_cut + 1, string_length - 1):
                if is_palindrome[first_cut + 1][second_cut] and is_palindrome[second_cut + 1][string_length - 1]:
                    return True
                    
    return False

Big(O) Analysis

Time Complexity
O(n^2) – Building the palindrome table takes O(n^2) operations because there are n^2 substring pairs. Checking all possible two cut locations also takes O(n^2) time since each check is an O(1) table lookup.
Space Complexity
O(n^2) – A 2D boolean array of size n by n is allocated to store whether each substring is a palindrome.

Optimal Solution

Approach

To figure out if a word can be chopped into three smaller palindromes, we can precompute which parts of the word are already palindromes. Then, we systematically test every possible way to make two cut marks to see if all three resulting pieces read the same forwards and backwards.

Here's how the algorithm would work step-by-step:

  1. First, examine every possible section of the word and figure out and remember which ones are palindromes.
  2. Think about making two cut marks through the word to divide it into three distinct pieces.
  3. Place the first cut mark somewhere in the first half of the word and check if the very first piece is a palindrome.
  4. If the first piece is a valid palindrome, place the second cut mark further along to create the middle and final pieces.
  5. Check if both the middle piece and the final piece are also palindromes.
  6. If you find a combination where all three pieces are palindromes, you have successfully solved the puzzle.
  7. If the current set of cuts does not work, move the cut marks and repeat the check until you test all possibilities or find a successful trio of palindromes.

Code Implementation

class Solution:
    def checkPartitioning(self, input_string: str) -> bool:
        string_length = len(input_string)
        palindrome_table = [[False] * string_length for _ in range(string_length)]

        # Precompute all palindrome substrings to ensure efficient validation of each piece in constant time.
        for substring_length in range(1, string_length + 1):
            for start_index in range(string_length - substring_length + 1):
                end_index = start_index + substring_length - 1
                if input_string[start_index] == input_string[end_index]:
                    if substring_length <= 2 or palindrome_table[start_index + 1][end_index - 1]:
                        palindrome_table[start_index][end_index] = True

        # Iterate through all possible cut pairs to test every possible way to divide into three parts.
        for first_cut in range(string_length - 2):
            if palindrome_table[0][first_cut]:
                for second_cut in range(first_cut + 1, string_length - 1):
                    if palindrome_table[first_cut + 1][second_cut] and palindrome_table[second_cut + 1][string_length - 1]:
                        # Return true immediately once a valid three-part palindrome partition is discovered.
                        return True

        return False

Big(O) Analysis

Time Complexity
O(n²) – To analyze the runtime, let n be the length of the input string. First, precomputing the palindrome status for every possible substring requires a double loop over all pairs of indices, resulting in n squared operations. Next, we test all possible pairs of cut marks using two nested loops to divide the string into three pieces, which also takes on the order of n squared operations. Combining these phases, the total operations approximate n squared plus n squared, which simplifies to O(n²).
Space Complexity
O(N^2) – To remember which sections of the word are palindromes as described in step 1, the algorithm utilizes a two-dimensional boolean table of size N by N, where N is the length of the input string. This preprocessing table represents the primary auxiliary data structure dominating the memory footprint. The systematic testing of cut marks in steps 2 through 7 requires only a constant amount of extra space for loop variables. Therefore, the overall extra memory scales quadratically with the input size, simplifying to Big O of N squared.

Edge Cases

String with length less than 3
How to Handle:
Since we need to partition the string into three non-empty substrings, any string of length 1 or 2 should immediately return false.
String of exactly length 3 with distinct characters
How to Handle:
The algorithm will correctly check if each single-character substring is a palindrome, returning true since single characters are always palindromes.
String with all identical characters
How to Handle:
Dynamic programming state transitions will easily identify valid palindrome cuts at any arbitrary index boundaries.
Maximum length constraints up to 2000 characters
How to Handle:
A naive backtracking approach would TLE, so we must precompute a 2D boolean palindrome table in O(N^2) time to scale efficiently.
No valid partition into three palindromes exists
How to Handle:
The nested loops will exhaust all possible cut combinations and naturally return false after failing to find a valid split.
Multiple overlapping valid palindrome partitions
How to Handle:
The algorithm only needs to find at least one valid combination, so returning true upon the first successful triplet match avoids redundant checks.
Memory limit constraints with large 2D boolean arrays
How to Handle:
Using a flat 1D array or optimizing the boolean grid storage prevents memory overhead issues in strict environments.