Palindrome partitioning
Advanced · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Palindrome partitioning cuts a string into pieces where every piece reads the same forwards and backwards, and lists all the ways to do so. You try a first piece, check it is a mirror word, then recurse on what remains. It teaches how to split text while checking a rule on each part.
Practical use cases
- Web app: Word game for kids. An educational spelling app shows a word like "aab" and asks the student to split it into mirror words such as "a|a|b" or "aa|b". The backend lists every valid split so the app can tell the student how many answers exist and which ones they missed.
- Web app: Text segmentation in a content tool. A content tool needs to cut a long string into pieces that all satisfy a rule, such as being a valid code or a known word. The same idea of try a first piece, check the rule, recurse on the rest, applies to splitting hashtags like "#goodmorningindia" into words. Trying the first word, checking it against a word list, and then splitting what remains means a 20-letter hashtag is cut into readable words for accessibility and search.
- System: DNA analysis. Biologists look for stretches of DNA that read the same as their mirror image, called palindromic regions. Breaking a long sequence into such regions follows this same cut-and-check pattern. These tools all follow the same rhythm of cutting off a piece, testing it, and recursing on the rest, which also appears in tokenisers and word splitters.
The story: Cutting the Mirror Rope
Kabir's favourite toy was a long rope of beads, each with a letter. One day the beads spelled aab. His sister Mira said: "Cut the rope into pieces so that each piece is a mirror word, one that reads the same from both ends, like a, aa or level."
Kabir took scissors and thought. The first piece could be "a" (a mirror). Then from the rest "ab" the next piece could be "a" again (mirror), leaving "b" (mirror too). That gives a | a | b. He wrote it in his notebook.
"But what if my first piece is longer?" he asked. He went back to the start and tried "aa" (still a mirror), then "b" (mirror). That is aa | b. He tried "aab" but backwards it was "baa", so he rejected it. And "ab" as a piece was rejected too.
Kabir learned the pattern: at each cut position, try every possible next piece; keep it only if it is a palindrome; then solve the rest of the rope the same way. If the whole rope is cut, save the pieces. This is palindrome partitioning.
How to spot this problem, and where you need it
You need to split a string into parts, and every part has to pass a test. There may be many ways to split, and you want all of them or one valid one.
Signs you need it
- The problem says "partition", "split into" or "cut the string" and gives a rule that each piece must satisfy.
- You try a first piece of length 1, 2, 3 and so on, and each choice changes what is left to solve.
- Checking every possible set of cut positions blindly is too slow, but you can reject bad pieces immediately.
Where to use it in a project
- Splitting a hashtag or long URL slug into dictionary words.
- Validating that a user-entered code can be broken into allowed segments.
The solution
Start at position 0. For each possible end position, take the piece from the start to that end. If the piece passes the rule, for example reads the same backwards, add it to your list and repeat from the end position. When you reach the end of the string, save the list of pieces as one answer. Then remove the last piece and try a longer one. Rejecting a bad piece early avoids exploring whatever follows it.
Payoff: Before: trying every possible way of cutting the word and checking afterwards. After: only splits with valid pieces are explored, finding all answers for a 10-letter word instantly.
Explain it like I am 8
A palindrome is a word that reads the same forwards and backwards, like "mom". You have a string of letters and a pair of scissors. Cut it into pieces where each piece is a mirror word. Try a short first piece, then a longer one, and see which ways work all the way to the end.
How it works, step by step
- Keep a start position (where the next piece begins) and the list of pieces chosen so far.
- Base case: if start reaches the end of the word, save a copy of the pieces.
- Try every possible end from start + 1 up to the end of the word. The piece is the slice between them.
- If the piece is not a palindrome, skip it. Otherwise choose it (add it to the pieces) and explore from its end.
- Un-choose: remove the piece, then try a longer one.
The code in four languages
PHP
<?php
// Every way to cut $s into pieces that are all palindromes.
function isPalindrome(string $t): bool {
$i = 0;
$j = strlen($t) - 1;
while ($i < $j) {
if ($t[$i++] !== $t[$j--]) return false; // two pointers walk inwards
}
return true;
}
function partition(string $s): array {
$result = [];
$pieces = [];
$explore = function (int $start) use (&$explore, &$result, &$pieces, $s) {
if ($start === strlen($s)) { // whole word cut
$result[] = $pieces;
return;
}
for ($end = $start + 1; $end <= strlen($s); $end++) {
$piece = substr($s, $start, $end - $start);
if (!isPalindrome($piece)) continue; // skip non-mirror pieces
$pieces[] = $piece; // choose
$explore($end); // explore
array_pop($pieces); // un-choose
}
};
$explore(0);
return $result;
}
foreach (partition('aab') as $p) {
echo implode(' | ', $p) . "\n";
}JavaScript
// Every way to cut s into pieces that are all palindromes.
function isPalindrome(t) {
let i = 0, j = t.length - 1;
while (i < j) {
if (t[i++] !== t[j--]) return false; // two pointers walk inwards
}
return true;
}
function partition(s) {
const result = [];
const pieces = [];
function explore(start) {
if (start === s.length) { // whole word cut
result.push([...pieces]);
return;
}
for (let end = start + 1; end <= s.length; end++) {
const piece = s.slice(start, end);
if (!isPalindrome(piece)) continue; // skip non-mirror pieces
pieces.push(piece); // choose
explore(end); // explore
pieces.pop(); // un-choose
}
}
explore(0);
return result;
}
for (const p of partition('aab')) {
console.log(p.join(' | '));
}Java
import java.util.*;
public class Main {
// Every way to cut s into pieces that are all palindromes.
static boolean isPalindrome(String t) {
int i = 0, j = t.length() - 1;
while (i < j) {
if (t.charAt(i++) != t.charAt(j--)) return false; // two pointers walk inwards
}
return true;
}
static List<List<String>> partition(String s) {
List<List<String>> result = new ArrayList<>();
explore(s, 0, new ArrayList<>(), result);
return result;
}
static void explore(String s, int start, List<String> pieces, List<List<String>> result) {
if (start == s.length()) { // whole word cut
result.add(new ArrayList<>(pieces));
return;
}
for (int end = start + 1; end <= s.length(); end++) {
String piece = s.substring(start, end);
if (!isPalindrome(piece)) continue; // skip non-mirror pieces
pieces.add(piece); // choose
explore(s, end, pieces, result); // explore
pieces.remove(pieces.size() - 1); // un-choose
}
}
public static void main(String[] args) {
for (List<String> p : partition("aab")) {
System.out.println(String.join(" | ", p));
}
}
}Go
package main
import (
"fmt"
"strings"
)
// isPalindrome: two pointers walk inwards.
func isPalindrome(t string) bool {
for i, j := 0, len(t)-1; i < j; i, j = i+1, j-1 {
if t[i] != t[j] {
return false
}
}
return true
}
// partition returns every way to cut s into pieces that are all palindromes.
func partition(s string) [][]string {
var result [][]string
var pieces []string
var explore func(start int)
explore = func(start int) {
if start == len(s) { // whole word cut
result = append(result, append([]string(nil), pieces...))
return
}
for end := start + 1; end <= len(s); end++ {
piece := s[start:end]
if !isPalindrome(piece) { // skip non-mirror pieces
continue
}
pieces = append(pieces, piece) // choose
explore(end) // explore
pieces = pieces[:len(pieces)-1] // un-choose
}
}
explore(0)
return result
}
func main() {
for _, p := range partition("aab") {
fmt.Println(strings.Join(p, " | "))
}
}Time: O(n × 2^n) · Extra space: O(n). A word of n letters has n-1 places to cut or not cut. Checking each piece costs up to n. Rejecting non-palindromes early prunes many branches.
Watch out for
- Cutting first and checking palindromes only at the end. Check each piece immediately and skip bad ones.
- Using
end < lengthin the loop and missing the last piece (the end index should reach the length). - Saving the live pieces array instead of a copy.
Quick check
- For "aab", which cut is NOT allowed?
- a | a | b
- aa | b
- a | ab
- All are allowed
- Where do we check whether a piece is a palindrome?
- Only at the end
- Never
- Before choosing the piece
- When do we save an answer?
- Whenever a piece is a palindrome
- When start reaches the end of the word
- When the pieces list is empty