1. Bitmask All Partitions + Post Validation
Intuition
For every mask from 0 to 2^(N-1) - 1, if bit i is set, place a partition after character i. Check whether every substring in the generated partition is palindromic.
Algorithm
- Step 1: Generate all 2^(N-1) possible string partitions.
- Step 2: For each partition, verify if every substring component is a valid palindrome.
- Step 3: If all parts are palindromes, add the partition list to result.
- Step 4: Return result list.
#include <iostream>#include <vector>#include <string> class Solution {public: bool isPalin(const std::string& s) { int l = 0, r = (int)s.size() - 1; while (l < r) { if (s[l++] != s[r--]) return false; } return true; } std::vector<std::vector<std::string>> allPalindromicPerms(std::string s) { int n = s.length(); std::vector<std::vector<std::string>> result; int total = 1 << (n - 1); for (int mask = 0; mask < total; mask++) { std::vector<std::string> current; int last = 0; bool valid = true; for (int i = 0; i < n - 1; i++) { if ((mask >> i) & 1) { std::string sub = s.substr(last, i - last + 1); if (!isPalin(sub)) { valid = false; break; } current.push_back(sub); last = i + 1; } } if (valid) { std::string sub = s.substr(last); if (isPalin(sub)) { current.push_back(sub); result.push_back(current); } } } return result; }}; int main() { Solution solver; std::vector<std::vector<std::string>> res = solver.allPalindromicPerms("geeks"); std::cout << "Bitmask Partitions for 'geeks':\n"; for (const auto& p : res) { std::cout << "[ "; for (const auto& w : p) std::cout << "\"" << w << "\" "; std::cout << "]\n"; } return 0;}Time & Space Complexity
- Time complexity:
O(2^N * N)— 2^(N-1) masks iterated, each taking O(N) time to split and validate. - Space complexity:
O(2^N * N)— Stores all partitions in memory.