Palindrome Partitioning - Python Solution

1. Introduction

The "Palindrome Partitioning" problem is a fascinating exercise in string manipulation and combinatorial algorithms. It requires partitioning a given string in such a way that each substring in the partition is a palindrome. A palindrome is a string that reads the same forward and backward. This problem is commonly encountered in coding interviews and tests one's ability to implement recursive solutions with backtracking.


Given a string s, the objective is to partition s such that every substring of the partition is a palindrome. The goal is to return all possible palindrome partitioning of s.

2. Solution Steps

1. Understand what constitutes a palindrome.

2. Use a backtracking approach to explore all possible partitions.

3. Check each substring to determine if it is a palindrome.

4. If a substring is a palindrome, recursively continue to partition the remaining string.

5. Collect and return all valid palindrome partitionings.

3. Code Program

def partition(s):
    def isPalindrome(sub):
        # Check if a substring is a palindrome
        return sub == sub[::-1]

    def backtrack(start, path):
        # If reached the end of the string, add the current partition to the result
        if start == len(s):
        for end in range(start + 1, len(s) + 1):
            # Check each substring
            if isPalindrome(s[start:end]):
                # If palindrome, add it to the path and continue partitioning
                backtrack(end, path + [s[start:end]])

    res = []
    backtrack(0, [])
    return res

# Testing the function with examples


[['a', 'a', 'b'], ['aa', 'b']]


1. Palindrome Check: The isPalindrome function checks if a given substring is a palindrome.

2. Backtracking Function: The backtrack function recursively explores partitions of the string.

3. Substring Exploration: For each starting point, the function iterates through all possible end points, creating substrings.

4. Recursive Partitioning: When a substring is a palindrome, it's added to the current path, and the function continues partitioning the remainder of the string.

5. Result Accumulation: Each time the end of the string is reached, a complete partitioning is added to the result list.

6. Unique Partitions: The function returns all the unique palindrome partitionings of the string.