Skip to problem
←

Palindrome Partitioning

Medium 0 attempts

Split s into nonempty, contiguous substrings so that every substring is a palindrome. Return all distinct valid partitions.

Each partition must preserve the original character order and use every character exactly once. You may place cuts between characters, but cannot rearrange, skip, or reuse characters. Return the substrings in their original order within each partition; the outer array may be in any order.

For s = "aab", the partitions are ["a", "a", "b"] and ["aa", "b"]. Return both, not just the partition with the fewest pieces. Every individual character is a palindrome, so at least one partition always exists.

Function contract

Implement partition(s).

Output: Return all distinct palindrome partitions. Preserve substring order inside each partition; outer array order does not matter.

Example 1

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

Example 2

Input
s = "a"
Output
[["a"]]
Constraints
  • 1 <= s.length <= 16
  • s consists of lowercase English letters

Backtracking over Cut Positions

At index start, try every nonempty substring beginning there. If it is a palindrome, append it to the current partition and recurse from the next character. Remove it when returning so the next choice starts with the same prefix of pieces.

When start reaches the end, copy the current partition into the result. Copying matters because backtracking subsequently changes the working array. Every partition corresponds to a unique sequence of cut positions, so this generates all valid partitions exactly once.

javascript
function partition(s) {
  const result = [];

  function isPalindrome(str, left, right) {
    while (left < right) {
      if (str[left] !== str[right]) return false;
      left++;
      right--;
    }
    return true;
  }

  function backtrack(start, current) {
    if (start === s.length) {
      result.push([...current]);
      return;
    }
    for (let end = start; end < s.length; end++) {
      if (isPalindrome(s, start, end)) {
        current.push(s.substring(start, end + 1));
        backtrack(end + 1, current);
        current.pop();
      }
    }
  }

  backtrack(0, []);
  return result;
}

Time: O(n × 2^n) in the worst case. There are up to 2^(n - 1) cut patterns, and copying all returned partitions already requires O(n × 2^n) work for a string of identical letters.

Space: O(n) auxiliary space for the recursion and current partition, excluding the result. The returned partitions require up to O(n × 2^n) space.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript