The Indian Engineer

Problem 131 Palindrome Partitioning

Posted on Last edited 4 mins

Backtracking Recursion Cpp

Problem Statement

Link - Problem 131

Question

Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.

Note to self

Example 1

Input: s = "aab"
Output: [["a","a","b"],["aa","b"]]

Example 2

Input: s = "a"
Output: [["a"]]

Additional Examples

s = "aaab"
output = [["a","a","a","b"],["a","aa","b"],["aa","a","b"],["aaa","b"]]

s = "abcaa"
output = [["a","b","c","a","a"],["a","b","c","aa"]]

s = "abbab"
output = [["a","b","b","a","b"],["a","b","bab"],["a","bb","a","b"],["abba","b"]]

s = "abaca"
output = [["a","b","a","c","a"],["a","b","aca"],["aba","c","a"]]

s = "aaa"
output = [["a","a","a"],["a","aa"],["aa","a"],["aaa"]]

Constraints

Solution

class Solution {
public:
    vector<vector<string>> partition(string s) {
        std::ios::sync_with_stdio(false);
        cin.tie(0);
        cout.tie(0);
        vector<vector<string>> result;
        vector<string> path;
        backtrack(s, 0, path, result);
        return result;
    }

private:
    void backtrack(const string& s, int start, vector<string>& path, vector<vector<string>>& result) {

        if (start == s.length())
        {
            result.push_back(path);
            return;
        }

        for (int end = start + 1; end <= s.length(); ++end)
        {
            if (isPalindrome(s, start, end - 1))
            {
                path.push_back(s.substr(start, end - start));
                backtrack(s, end, path, result);
                path.pop_back();
            }
        }
    }

    bool isPalindrome(const string& s, int left, int right) {

        while (left < right)
        {
            if (s[left++] != s[right--])
                return false;
        }
        return true;
    }
};

Complexity Analysis

Explanation

1. Intuition

2. Implementation

3. Dry Run

Input: s = "aab"
Output: [["a","a","b"],["aa","b"]]

This solution uses backtracking to generate all possible palindrome partitions of the input string. By exploring all possible partitions, it ensures that no valid partition is missed, resulting in a complete set of palindrome partitions.