Start learning free

LESSON 131 OF 314 · BACKTRACKING

Palindrome Partitioning in C++: Backtracking in O(n * 2^n)

Practice O(n · 2ⁿ) Read the full explanation

You get a string s of lowercase letters. Return every way to cut s into pieces that are all palindromes.

A palindrome reads the same backwards, like "level". A single letter is a palindrome too.

The pieces keep the letters in their order. Each letter goes into exactly one piece. Write each way as a vector of its pieces, from left to right.

List the ways by their first piece, shortest first. When two ways share a first piece, compare their second pieces the same way. Then the third, and so on.

That is the order you get when you always try the shortest next piece first.

 

Example 1:

Input: s = "noon"
Output: [["n","o","o","n"],["n","oo","n"],["noon"]]
Explanation: Every single letter is a palindrome.
"oo" in the middle is a palindrome too.
So is the whole word "noon".
The two ways that start with "n" come first.
Between them, "o" is shorter than "oo".

Example 2:

Input: s = "cat"
Output: [["c","a","t"]]
Explanation: "ca", "at" and "cat" are not palindromes.
So each letter must be its own piece.

Example 3:

Input: s = "bbb"
Output: [["b","b","b"],["b","bb"],["bb","b"],["bbb"]]
Explanation: Any run of b's is a palindrome.
The first pieces are "b", "b", "bb" and "bbb".
Two ways start with "b".
Their second pieces, "b" and "bb", put them in order.

Constraints:
  • s has 1 to 12 letters.
  • Each letter is a lowercase English letter, from a to z.
Note:

Your solution should run in O(n · 2ⁿ) time, where n is the length of s.


Hints:

Choose the first piece. It starts at the first letter and must be a palindrome. Then cut the rest of the string the same way.

Use backtracking. A helper gets start, the first letter not yet in a piece. It tries every end from start on. When the letters from start to end form a palindrome, it adds that piece. Then it calls itself from end + 1 and removes the piece again. When start reaches the end of s, the pieces are one full way: save a copy.

Between two neighbouring letters you either cut or you don't. So there are at most 2ⁿ⁻¹ ways. Checking and copying one way takes O(n): O(n · 2ⁿ) time.
Besides the answer, the pieces being built and the open calls take O(n) extra space.
STEP 1 OF 18
    Ctrl + Enter to check

    C++ · BACKTRACKING

    Palindrome Partitioning in C++, explained

    Problem overview

    The method partition gets a string s of 1 to 12 lowercase letters and returns every way to cut it into pieces that are all palindromes. A palindrome reads the same backwards, and a single letter is one. The pieces keep the letters in order and every letter lands in exactly one piece. A way is a vector<string>, and the answer is a vector<vector<string>> of ways.

    The ways must come in a fixed order: by first piece, shortest first, then by second piece, and so on. That is the order produced by always trying the shortest next piece first.

    For "noon" the answer is [["n","o","o","n"],["n","oo","n"],["noon"]]. For "cat" it is [["c","a","t"]], since "ca", "at" and "cat" are not palindromes. For "bbb" it is [["b","b","b"],["b","bb"],["bb","b"],["bbb"]].

    Approach: choose the first piece, then cut the rest

    Every valid way starts with a first piece that begins at the first letter and is a palindrome. Try each possible length for it. For each palindromic first piece, the rest of the string must be cut the same way, which is a smaller version of the same problem. When the cut reaches the end of the string, the pieces chosen so far are one complete way.

    That is backtracking: add a piece, recurse, then remove the piece and try the next length. The order falls out of the loop. Trying end from start upwards tries the shortest piece first, and the recursion explores everything after that piece before moving on to a longer one.

    Between every two neighbouring letters you either cut or you don't, so there are at most 2^(n-1) ways. Checking a piece and copying a finished way each take O(n), which gives the lesson's O(n * 2^n) bound. The worst input is a string of one repeated letter: twelve a's have 2048 ways, while twelve different letters have only one.

    A trace of "noon": the first piece "n" leaves "oon". There, "o" leaves "on", where "o" leaves "n", which gives the way n, o, o, n. Back at "on", "on" is not a palindrome, so the loop ends. Back at "oon", the piece "oo" leaves "n", which gives n, oo, n. The piece "oon" is not a palindrome. Back at the top, the first pieces "no" and "noo" are not palindromes and are skipped. Finally "noon" is a palindrome and uses the whole string, giving noon.

    Step by step

    1. Create result, a vector<vector<string>> that collects the finished ways.
    2. Create current, a vector<string> holding the pieces of the way being built.
    3. Start the search: backtrack(s, 0, current, result). The 0 means no letter is in a piece yet.
    4. Return result.
    5. Declare backtrack. It returns void and takes s, start (the first letter not yet in a piece), current and result.
    6. Base case. If start == s.size(), every letter is in a piece.
    7. Save a copy of current with push_back and return.
    8. Loop over the piece's end, from start up to the last index.
    9. Test the piece from start to end with isPalindrome.
    10. Take the piece: s.substr(start, end - start + 1) goes onto current.
    11. Recurse from end + 1.
    12. Undo the choice with pop_back(), so the loop can try a longer piece.
    13. Write isPalindrome. It takes s, start and end. Two indexes, left and right, walk towards each other.
    14. Compare in pairs. While left < right, a differing pair returns false; otherwise both indexes move inward.
    15. Return true when the loop finishes. A one-letter piece never enters the loop, so it is a palindrome.

    The solution in C++

    class Solution {
    public:
        vector<vector<string>> partition(string s) {
            vector<vector<string>> result;
            vector<string> current;
            backtrack(s, 0, current, result);
            return result;
        }
    
        void backtrack(string& s, int start, vector<string>& current, vector<vector<string>>& result) {
            if (start == s.size()) {
                result.push_back(current);
                return;
            }
            for (int end = start; end < s.size(); end++) {
                if (isPalindrome(s, start, end)) {
                    current.push_back(s.substr(start, end - start + 1));
                    backtrack(s, end + 1, current, result);
                    current.pop_back();
                }
            }
        }
    
        bool isPalindrome(string& s, int start, int end) {
            int left = start;
            int right = end;
            while (left < right) {
                if (s[left] != s[right]) {
                    return false;
                }
                left++;
                right--;
            }
            return true;
        }
    };
    

    The C++ details worth a closer look:

    • substr(pos, length), not two positions. The second argument is a length, which is why the piece uses end - start + 1. Passing end would take too many letters whenever start is above 0.
    • push_back(current) stores a copy. current keeps changing as the search goes on, but each saved way is independent, so later pop_back() calls do not damage it.
    • References as parameters. s, current and result are passed with &. Without it each call would copy the string and the vectors, and changes to current and result would not reach the caller.
    • Signed and unsigned. start == s.size() and end < s.size() compare an int with an unsigned size_t. The indexes here are never negative, so the comparisons are correct, though a compiler may warn about them.

    Complexity

    Time is O(n * 2^n): up to 2^(n-1) ways, each costing O(n) to check and copy. Besides the answer, the extra space is O(n): the pieces in current and the open calls, at most n deep.

    Edge cases and common mistakes

    • Forgetting pop_back(). Pieces would pile up in current, and the later ways would contain pieces from earlier choices.
    • Wrong palindrome bounds. isPalindrome takes inclusive start and end indexes. Passing end + 1 checks one letter too many.
    • Recursing from end instead of end + 1. The last letter would be used twice, and the search would not stop.
    • One letter. For "a" the answer is [["a"]].
    • Several letters but one way. A string with no palindromes longer than one letter, such as "cat", has exactly one way: every letter on its own.

    Testing

    The function printed these results:

    sResult
    "noon"[["n","o","o","n"],["n","oo","n"],["noon"]]
    "aab"[["a","a","b"],["aa","b"]]
    "a"[["a"]]
    "aaaaaaaaaaaa"2048 ways
    "abcdefghijkl"1 way
    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free