Skip to problem
←

Palindrome Partitions Using Bitmasks

Medium 0 attempts

Given a string s, return every way to split it into nonempty contiguous substrings such that each substring is a palindrome. Preserve the original character order and use each character exactly once.

Use a bitmask over cut positions to enumerate candidate partitions. For a string of length n, there are n - 1 gaps. Bit i indicates whether to cut after character s[i]; a zero bit leaves that gap joined.

For s = "aab", mask 0 gives ["aab"], mask 1 gives ["a", "ab"], mask 2 gives ["aa", "b"], and mask 3 gives ["a", "a", "b"]. Only the last two partitions qualify.

Return all qualifying partitions exactly once, in any outer order. Preserve substring order within each partition. A single-character string has one partition, and splitting every character individually always gives a valid partition. Return the partitions rather than printing them.

Function contract

Implement allPalindromicPartitions(s).

Output: Return every distinct palindrome partition once. Substrings retain their original order; outer result 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 <= 15
  • s consists of lowercase English letters.

Enumerate Cut Masks and Check Each Piece

A string of length n has n - 1 possible cut positions between characters. Each bitmask from 0 to 2^(n-1) - 1 represents one way to partition the string — a set bit means "cut here." For each bitmask, extract the substrings and check if all of them are palindromes.

javascript
function allPalindromicPartitions(s) {
  const n = s.length;
  const results = [];

  function isPalin(str) {
    let l = 0,
      r = str.length - 1;
    while (l < r) {
      if (str[l] !== str[r]) return false;
      l++;
      r--;
    }
    return true;
  }

  for (let mask = 0; mask < 1 << (n - 1); mask++) {
    const parts = [];
    let start = 0;
    let valid = true;

    for (let i = 0; i < n - 1; i++) {
      if (mask & (1 << i)) {
        const part = s.substring(start, i + 1);
        if (!isPalin(part)) {
          valid = false;
          break;
        }
        parts.push(part);
        start = i + 1;
      }
    }

    if (!valid) continue;
    const last = s.substring(start);
    if (isPalin(last)) {
      parts.push(last);
      results.push(parts);
    }
  }
  return results;
}

Time Complexity: O(2^(n-1) × n) — iterate all bitmasks and check palindromes

Space: O(n) temporary space for the candidate partition, plus up to O(n × 2^(n - 1)) for all returned partitions.

Every possible partition has one unique cut mask, so enumeration is complete and produces no duplicate partitions. The n <= 15 constraint keeps the shifts within JavaScript’s signed 32-bit bitwise range.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript