Abstract flowing gradient in deep indigo and blue tones, smooth and luminous, evoking a modern digital learning atmosphere

Computer Science and programming articles. We do not sell courses.

Solving palindrome partitioning with backtracking

Take a string and ask a deceptively simple question: where should it be cut so that every resulting piece reads the same forwards and backwards? The string aab, for instance, splits cleanly into aa and b. The string abacdc splits into aba and cdc, while racecar needs no cuts at all. The task is to find those cut positions, and for most strings there are several valid answers, not one. Learn more about How To Use Python S Multiprocessing For Parallel Computing.

This is the shape of a classic backtracking problem, the same family that appears in LeetCode's partitioning challenge asking for the minimum number of cuts. The naive strategy is exhaustive and honest: try every possible first cut, recurse on whatever remains, and keep the arrangements that satisfy the constraint. That brute-force approach is worth understanding properly, because it teaches how a recursion explores a search space, how a valid path is built, and how pruning rescues a program that would otherwise wander into an exponential number of dead ends. Learn more about Algorithms.

What palindrome partitioning actually asks

A partition divides a string into contiguous, non-empty substrings. The constraint is that each substring must equal its own reverse. Note the word contiguous: a solution cannot gather scattered characters into a piece, so this differs from problems about rearranging letters or finding palindromic subsequences. The cut positions are the only freedom you have, and the string's order is fixed.

Three variants show up often. The first asks you to return every valid partition, which turns the algorithm into an enumerator. The second asks for the minimum number of cuts needed, so the search can stop as soon as it finds a short answer. The third fixes a target count of pieces, asking whether a split into exactly that many palindromic chunks exists. All three share the same underlying mechanics, and the enumerating version is the easiest place to learn them.

Work by hand before reaching for a keyboard. For aab, the first piece could be a (leaving ab, which fails since ab is not a palindrome) or aa (leaving b, which succeeds). Only one partition survives. For aabb, both aa and bb are palindromes, and the valid partitions are ["aa", "bb"] and ["aabb"]. Small examples expose the branching more clearly than long ones do.

Why backtracking is the natural fit

At any position in the string, the only decision is where the current piece ends. Pick an end index, test whether the slice is a palindrome, and if it is, recurse on the remainder. When the recursion returns without success, undo that choice and try a longer piece. This is textbook depth-first search: descend as far as possible along one branch, then backtrack to the last decision point and try the next alternative.

The search space grows fast. A string of length n has n − 1 possible internal cut positions, and each subset of those positions defines a partition, giving 2^(n−1) arrangements in total before the palindrome constraint removes any. For a string of all a characters, every arrangement survives, so the unpruned search really does visit that many nodes.

Australians will recognise the rhythm of the algorithm in the road rules: keep left, and let the car ahead clear first. The recursion works the same way, keeping the earliest cut as its first preference and only advancing when the current path fails. A single wrong choice never ends the journey; it simply sends you back to the previous fork.

Checking whether a piece reads the same backwards

A palindrome test with two pointers is cheap and easy to reason about. Place one pointer at the start of the candidate piece and one at its end, compare the characters, and walk them towards each other. A single mismatch rejects the piece immediately.

def is_palindrome(text: str, left: int, right: int) -> bool:
    while left < right:
        if text[left] != text[right]:
            return False
        left += 1
        right -= 1
    return True

Passing indices rather than a sliced string matters in Python. Slicing text[left:right + 1] allocates a new string of length m and copies it, so testing every candidate this way quietly adds an O(m) allocation on top of the O(m) comparison. Working with indices keeps the check allocation-free and lets the same helper serve the whole recursion.

For very short pieces, comparing piece == piece[::-1] is compact and perfectly fine. For long ones, the pointer version scales better and, more importantly, makes the invariant obvious to anyone reading the code.

A complete backtracking implementation

Here is the enumerating version written out, with the recursion state split into the current position and the list of pieces chosen so far.

def palindrome_partitions(text: str) -> list[list[str]]:
    results = []

    def backtrack(start: int, path: list[str]) -> None:
        if start == len(text):
            results.append(path.copy())
            return

        for end in range(start, len(text)):
            if is_palindrome(text, start, end):
                path.append(text[start:end + 1])
                backtrack(end + 1, path)
                path.pop()

    backtrack(0, [])
    return results

The append and pop pair is the backtracking mechanism. Appending records the decision to cut after end; popping undoes it so the next candidate can be tried from the same state. At the base case, path.copy() is necessary because the list is mutated later on, so storing the reference directly would give every result the same final contents.

A useful refinement appears once the pieces get long. If the entire remaining suffix text[start:] is itself a palindrome, there is no point testing shorter candidates: no split of a palindrome can produce fewer pieces than one, so the recursion can finish immediately.

        if is_palindrome(text, start, len(text) - 1):
            path.append(text[start:])
            results.append(path.copy())
            path.pop()
            return

That single check turns a large amount of unnecessary branching into an early exit, particularly on strings made of repeated characters.

Counting partitions and measuring the search cost

Because a partition is determined by its cut positions, the number of valid partitions of a string of length n is at most 2^(n−1). Every node in the search performs at least one palindrome check costing O(n), so the unpruned worst-case runtime lands around O(n · 2^n), with O(n) auxiliary space for the recursion stack and the current path. The exponential term is not an artefact of clumsy coding; it reflects the genuine size of the answer set.

The number of partitions of a string into any number of pieces follows the Bell numbers, which grow faster than 2^n as n climbs. By contrast, when only the minimum cut count matters, a dynamic programming table answers the question in O(n²) time and O(n) space.

def minimum_cuts(text: str) -> int:
    n = len(text)
    if n == 0:
        return 0
    pieces = [0] * n
    for end in range(1, n):
        for start in range(end, -1, -1):
            chunk = text[start:end + 1]
            if chunk == chunk[::-1]:
                pieces[end] = pieces[start - 1] + 1 if start > 0 else 1
                break
    return pieces[-1] - 1

Here pieces[end] stores the fewest pieces covering the prefix ending at end. The inner loop scans backwards from the longest candidate, and the first palindromic chunk it finds gives the best value because a longer prefix never needs fewer pieces. Readers who want the wider family of search techniques can browse the algorithm walk-throughs collected on the site, which use similar decomposition and pruning ideas.

Where pruning and parallelism change the picture

Three optimisations carry most of the practical weight. Precomputing a table of palindrome ranges costs O(n²) once and turns every later check into a constant-time lookup. Memoising the recursion on the starting index removes repeated work whenever two different cut sequences reach the same suffix with the same remaining task. Pruning, as shown earlier, ends a branch the moment the whole suffix forms a valid final piece.

from functools import lru_cache

def minimum_cuts_memo(text: str) -> int:
    n = len(text)
    pal = [[False] * n for _ in range(n)]
    for i in range(n - 1, -1, -1):
        for j in range(i, n):
            pal[i][j] = text[i] == text[j] and (j - i < 2 or pal[i + 1][j - 1])

    @lru_cache(maxsize=None)
    def solve(start: int) -> int:
        if start == n:
            return 0
        best = n
        for end in range(start, n):
            if pal[start][end]:
                best = min(best, 1 + solve(end + 1))
        return best

    return solve(0) - 1

Parallelism is a different kind of lever. Each first cut produces an independent subproblem, so the branches could be farmed out to separate processes; the trade-offs in queueing overhead and serialisation are explained in the Python multiprocessing guide. For teaching, though, the sequential version is usually clearer, and interview panels in Sydney, Melbourne and Brisbane rarely ask for parallel versions. What they do reward is a candidate who can state the complexity honestly and explain where the exponential growth comes from.

Habits that make the solution stick

A few working habits separate a clean solution from a lucky one. The following recommendations apply to any partitioning problem, palindrome or not.

The appeal of this problem is that the search is small enough to hold in your head yet rich enough to teach something real. The same pattern of choose, test, recurse and undo shows up in subset sum, word break, N-queens and constraint scheduling. Python remains the natural language for experimenting with these ideas, and it is the language most teams in the Australian market reach for when they need to move from a script to a service.

Once the mechanics click, the pattern generalises quickly. Write the cut decision, respect the constraint, and let the recursion do the bookkeeping. If a branch leads nowhere, backing up to the previous fork is not failure; it is the algorithm working as designed, keeping left and trying again.