AlgoInsight

DSA problem

Palindrome Partitioning

MediumBacktrackingPattern: Backtrackingtop150AmazonMicrosoftGoogleBloombergUber

Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitionings of s. A palindrome is a string that reads the same forwards and backwards (single characters and the empty string both count).

For example, s = "aab" can be partitioned as ["a", "a", "b"] (three palindromes of length 1) or ["aa", "b"] (one palindrome of length 2 followed by one of length 1). The complete answer is the set of all valid such partitions.

The cleanest formulation is backtracking with a start index. At each recursive call we try every end from start to n - 1; if the substring s[start..end] is a palindrome, we add it to the current partition, recurse with the new start at end + 1, and undo. When start == n we have consumed the entire string and the current partition is a valid one, so we snapshot it into the results.

For speed we precompute a palindrome DP table isPal[i][j] in O(n^2) time and space: isPal[i][j] is true if s[i..j] is a palindrome, computed bottom-up using the recurrence isPal[i][j] = (s[i] == s[j]) && (j - i < 2 || isPal[i + 1][j - 1]). This turns each palindrome check inside the recursion into an O(1) lookup. Total time is bounded by O(n * 2^n) because there are up to 2^(n - 1) partitions and each costs O(n) to materialize.

Examples

Example 1
Input: s = "aab"
Output: [["a","a","b"],["aa","b"]]
Explanation: Two valid palindrome partitions. Splitting into ["a","ab"] is invalid because "ab" is not a palindrome.
Example 2
Input: s = "a"
Output: [["a"]]
Explanation: A single character is itself a palindrome, so the only partition is the singleton.
Example 3
Input: s = "aaba"
Output: [["a","a","b","a"],["a","aba"],["aa","b","a"]]
Explanation: Three palindrome partitions exist. Note that ["aab","a"] fails because "aab" is not a palindrome.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

backtrackingstringdynamic-programmingrecursion

Browse all DSA problems