{"id":9507,"date":"2025-08-20T16:34:27","date_gmt":"2025-08-20T11:04:27","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=9507"},"modified":"2025-10-13T15:40:33","modified_gmt":"2025-10-13T10:10:33","slug":"palindrome-partitioning","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/palindrome-partitioning\/","title":{"rendered":"Palindrome Partitioning"},"content":{"rendered":"\n<!-- Palindrome_11 -->\n<link\n    href=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/themes\/prism-tomorrow.min.css\"\n    rel=\"stylesheet\"\n\/>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/prism.min.js\"><\/script>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/plugins\/autoloader\/prism-autoloader.min.js\"><\/script>\n\n<style>\n.wp_blog_theme {\n  --primary: #E58C32;\n  --secondary: #030302;\n  --light-bg: #fef9f4;\n  --text-dark: #2d2d2d;\n  --tab-radius: 12px;\n  --shadow: 0 4px 12px rgba(0, 0, 0, 0.08);\n  --code-bg: #001f3f;\n  --code-text: #d4f1ff;\n}\n\n.wp_blog_container {\n  font-family: 'Segoe UI', sans-serif;\n  background: var(--light-bg);\n  margin: 0;\n  padding: 0;\n  color: var(--text-dark);\n}\n\n\/* Heading *\/\n.wp_blog_main-heading {\n  text-align: center;\n  font-size: 2.4rem;\n  color: var(--primary);\n  margin-top: 2.5rem;\n  font-weight: bold;\n}\n\n\/* Explanation Card *\/\n.wp_blog_explanation,\n.wp_blog_code-tabs-container {\n  max-width: 940px;\n  margin: 2rem auto;\n  padding: 2rem;\n  background: white;\n  border-radius: var(--tab-radius);\n  box-shadow: var(--shadow);\n}\n\n\/* Text and Visuals *\/\n.wp_blog_explanation h2 {\n  font-size: 1.4rem;\n  color: var(--primary);\n  margin-bottom: 0.5rem;\n}\n\n.wp_blog_explanation p,\n.wp_blog_explanation li {\n  font-size: 1.05rem;\n  line-height: 1.7;\n  margin: 0.5rem 0;\n}\n\n.wp_blog_explanation code {\n  background: #fef9f4;   \/* light bg instead of dark blue *\/\n  color: #E58C32;        \/* brand orange *\/\n  padding: 3px 6px;\n  border-radius: 4px;\n  font-family: 'Courier New', monospace;\n  font-weight: 600;      \/* optional, makes it pop *\/\n}\n\n.wp_blog_explanation img {\n  max-width: 100%;\n  border-radius: var(--tab-radius);\n  margin-top: 1rem;\n  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);\n}\n\n\/* Tab Buttons *\/\n.wp_blog_code-tabs-header {\n  display: flex;\n  flex-wrap: wrap;\n  gap: 0.5rem;\n  margin-bottom: 1rem;\n}\n\n.wp_blog_code-tab-button {\n  padding: 0.6rem 1.2rem;\n  border: 1px solid var(--primary);\n  background: white;\n  color: var(--primary);\n  border-radius: 50px;\n  font-weight: 600;\n  cursor: pointer;\n  transition: all 0.3s ease;\n}\n\n.wp_blog_code-tab-button:hover {\n  background: var(--secondary);\n}\n\n.wp_blog_code-tab-button.active {\n  background: var(--primary);\n  color: white;\n}\n\n\/* Code Content *\/\n.wp_blog_code-tab-content {\n  display: none;\n  background: var(--code-bg);\n  border-radius: var(--tab-radius);\n}\n\n.wp_blog_code-tab-content.active {\n  display: block;\n}\n\n.wp_blog_code-tab-content pre {\n  margin: 0;\n  padding: 1.5rem;\n  font-size: 1rem;\n  overflow-x: auto;\n  background: var(--code-bg);\n  border-radius: var(--tab-radius);\n  color: var(--code-text);\n}\n\n\/* Dark mode variables *\/\n.wp_blog_theme.dark-mode {\n  --light-bg: #121212;\n  --text-dark: #f5f5f5;\n  --shadow: 0 4px 12px rgba(255, 255, 255, 0.08);\n  --code-bg: #1e1e1e;\n  --code-text: #c5f0ff;\n}\n\n.wp_blog_theme.dark-mode .wp_blog_explanation {\n  background: #1e1e1e;\n}\n\n\/* Dark mode code highlight *\/\n.wp_blog_theme.dark-mode .wp_blog_explanation code {\n  background: #333;\n  color: #ffd27f;\n}\n\n.wp_blog_theme {\n  position: relative; \/* makes it the reference for absolute children *\/\n}\n\n.wp_blog_toggle-btn {\n  position: absolute;\n  top: 1rem;\n  right: 1rem;\n  z-index: 9999;\n  padding: 0.5rem 0.8rem;\n  border-radius: 10%;\n  background: var(--primary);\n  color: white;\n  font-weight: bold;\n  cursor: pointer;\n  border: none;\n  box-shadow: var(--shadow);\n  transition: background 0.3s, transform 0.2s;\n}\n\n.wp_blog_toggle-btn:hover {\n  background: #cc772e;\n}\n\n.wp_blog_theme.dark-mode .wp_blog_code-tabs-container {\n  background: #1e1e1e;\n}\n<\/style>\n\n<div class=\"wp_blog_container wp_blog_theme\">\n<button id=\"blogNotesThemeToggle\" class=\"wp_blog_toggle-btn\">\ud83c\udf19<\/button>\n<h1 class=\"wp_blog_main-heading\"><\/h1>\n\n<div class=\"wp_blog_explanation\">\n    <h2>Problem Statement<\/h2>\n    <p>\n        Given a string s, partition <code>s<\/code> such that every substring of the partition is a palindrome. Return <i>all possible palindrome partitioning of <code>s<\/code><\/i>.\n    <\/p>\n\n    <p><strong>Example 1:<\/strong><\/p>\n    <p><strong>Input:<\/strong> s = &#8220;aab&#8221;<\/p>\n    <p><strong>Output:<\/strong><code> \n        [[\"a\",\"a\",\"b\"],[\"aa\",\"b\"]]\n<\/code><\/p>\n\n    <p><strong>Example 2:<\/strong><\/p>\n    <p><strong>Input:<\/strong> s = &#8220;a&#8221;<\/p>\n    <p><strong>Output:<\/strong><code> [[\"a\"]]<\/code><\/p>\n\n    <h2>Constraints<\/h2>\n    <ul>\n        <li><code>1 <= s.length <= 16<\/code><\/li>\n        <li><code>s<\/code> contains only lowercase English letters.<\/li>\n    <\/ul>\n\n    <h2>Approach<\/h2>\n   <ul>\n    <li><strong>Backtracking<\/strong> \u2013 We try to partition the string into all possible substrings.<\/li>\n    <li>t each step, take a prefix <code>(choice = s[0..i])<\/code>\n        <ul>\n            <li>If it\u2019s a <strong>palindrome<\/strong>, include it in the <code>current path and recursively partition<\/code> the remaining string.<\/li>\n            <li>If not, <code>skip it<\/code>.<\/li>\n        <\/ul>\n    <\/li>\n    <li>When the <strong>remaining string becomes empty<\/strong>, we\u2019ve found a valid partition \u2192 add it to the result.<\/li>\n    <li>Use backtracking to <code>explore all<\/code> possibilities (push \u2192 recurse \u2192 pop).<\/li>\n    <li><code>isPalindrome<\/code> is used to check <strong>substrings<\/strong> in O(n) time.<\/li>\n   <\/ul> \n\n    <h2>Time Complexity<\/h2>\n    <li><p><strong>Time Complexity = O(n * 2<sup>n<\/sup>)<\/strong><\/p><\/li> \n    <h2>Space Complexity<\/h2>\n    <li><p><strong>Space Complexity =  O(n)<\/strong><\/p><\/li>\n\n<h2>Dry Run<\/h2>\n<div style=\"border-left: 4px solid var(--primary); padding: 1rem; border-radius: var(--tab-radius); margin: 1rem 0;\">\n<p><strong>Input:<\/strong><\/p>\n<pre> s = \"aab\" <\/pre>\n\n<p><strong>State Transitions:<\/strong><\/p>\n<pre>\nInitialize: result = []\nCall backtrack([], \"aab\")\n\nLevel 1:\nLoop i = 1 \u2192 choice = \"a\" (palindrome)\npath.push(\"a\") \u2192 path = [\"a\"]\nCall backtrack([\"a\"], \"ab\")\n\n    Level 2:\n    Loop i = 1 \u2192 choice = \"a\" (palindrome)\n    path.push(\"a\") \u2192 path = [\"a\",\"a\"]\n    Call backtrack([\"a\",\"a\"], \"b\")\n\n        Level 3:\n        Loop i = 1 \u2192 choice = \"b\" (palindrome)\n        path.push(\"b\") \u2192 path = [\"a\",\"a\",\"b\"]\n        remainingString empty \u2192 result.push([\"a\",\"a\",\"b\"])\n        path.pop() \u2192 path = [\"a\",\"a\"]\n\n    path.pop() \u2192 path = [\"a\"]\n\n    Loop i = 2 \u2192 choice = \"ab\" (not palindrome) \u2192 skip\n\npath.pop() \u2192 path = []\n\nLoop i = 2 \u2192 choice = \"aa\" (palindrome)\npath.push(\"aa\") \u2192 path = [\"aa\"]\nCall backtrack([\"aa\"], \"b\")\n\n    Level 2:\n    Loop i = 1 \u2192 choice = \"b\" (palindrome)\n    path.push(\"b\") \u2192 path = [\"aa\",\"b\"]\n    remainingString empty \u2192 result.push([\"aa\",\"b\"])\n    path.pop() \u2192 path = [\"aa\"]\n\npath.pop() \u2192 path = []\n\nLoop i = 3 \u2192 choice = \"aab\" (not palindrome) \u2192 skip\n<\/pre>\n\n<p><strong>Final Output:<\/strong> <code>[[\"a\",\"a\",\"b\"], [\"aa\",\"b\"]]<\/code><\/p>\n\n<p><strong>Explanation:<\/strong> \nThe algorithm explores all possible partitions of the string. \nAt each step, it only proceeds if the chosen substring is a palindrome. \nFor \"aab\", the valid partitions are:\n- \"a\" | \"a\" | \"b\"\n- \"aa\" | \"b\"\n<\/p>\n<\/div>\n<\/div>\n\n<div class=\"wp_blog_code-tabs-container\">\n    <div class=\"wp_blog_code-tabs-header\">\n        <button class=\"wp_blog_code-tab-button active\" data-lang=\"js\">JavaScript<\/button>\n        <button class=\"wp_blog_code-tab-button\" data-lang=\"py\">Python<\/button>\n        <button class=\"wp_blog_code-tab-button\" data-lang=\"java\">Java<\/button>\n        <button class=\"wp_blog_code-tab-button\" data-lang=\"cpp\">C++<\/button>\n        <button class=\"wp_blog_code-tab-button\" data-lang=\"c\">C<\/button>\n        <button class=\"wp_blog_code-tab-button\" data-lang=\"cs\">C#<\/button>\n    <\/div>\n\n    <div class=\"wp_blog_code-tab-content active\" data-lang=\"js\">\n<pre><code class=\"language-javascript\">\nvar partition = function(s) {\n    let result = []; \n    let isPalindrome = (s) => { \n        let i =0; \n        let j = s.length - 1; \n    while(i < j) { \n        if(s[i++] != s[j--]) \n        return false; \n    } \n    return true; \n  } \n  let backtrack = (path, remainingString) => { \n    if(!remainingString.length) { \n        result.push([...path]);\n    } \n    for(let i=1; i <= remainingString.length; i++){ \n        let choice = remainingString.substring(0, i); \n        if(!isPalindrome(choice)) \n         continue; \n         path.push(choice); \n         backtrack(path, remainingString.substring(i)); \n         path.pop(); \n        } \n    } backtrack([], s); \n    return result;\n};\n<\/code><\/pre>\n<\/div>\n\n<div class=\"wp_blog_code-tab-content\" data-lang=\"py\">\n<pre><code class=\"language-python\">\nclass Solution:\n    def partition(self, s: str):\n        result = []\n\n        def isPalindrome(sub):\n            return sub == sub[::-1]\n\n        def backtrack(path, remaining):\n            if not remaining:\n                result.append(path[:])\n                return\n            for i in range(1, len(remaining) + 1):\n                choice = remaining[:i]\n                if not isPalindrome(choice):\n                    continue\n                path.append(choice)\n                backtrack(path, remaining[i:])\n                path.pop()\n\n        backtrack([], s)\n        return result\n<\/code><\/pre>\n<\/div>\n\n<div class=\"wp_blog_code-tab-content\" data-lang=\"java\">\n<pre><code class=\"language-java\">\nimport java.util.*;\n\nclass Solution {\n    public List<List<String>> partition(String s) {\n        List<List<String>> result = new ArrayList<>();\n        backtrack(s, new ArrayList<>(), result);\n        return result;\n    }\n\n    private boolean isPalindrome(String s) {\n        int i = 0, j = s.length() - 1;\n        while (i < j) {\n            if (s.charAt(i++) != s.charAt(j--)) return false;\n        }\n        return true;\n    }\n\n    private void backtrack(String remaining, List<String> path, List<List<String>> result) {\n        if (remaining.isEmpty()) {\n            result.add(new ArrayList<>(path));\n            return;\n        }\n        for (int i = 1; i <= remaining.length(); i++) {\n            String choice = remaining.substring(0, i);\n            if (!isPalindrome(choice)) continue;\n            path.add(choice);\n            backtrack(remaining.substring(i), path, result);\n            path.remove(path.size() - 1);\n        }\n    }\n}\n<\/code><\/pre>\n<\/div>\n\n<div class=\"wp_blog_code-tab-content\" data-lang=\"cpp\">\n<pre><code class=\"language-cpp\">\nclass Solution {\npublic:\n    vector<vector<string>> partition(string s) {\n        vector<vector<string>> result;\n        vector<string> path;\n        backtrack(s, path, result);\n        return result;\n    }\nprivate:\n    bool isPalindrome(string &s) {\n        int i = 0, j = s.size() - 1;\n        while (i < j) {\n            if (s[i++] != s[j--]) return false;\n        }\n        return true;\n    }\n    void backtrack(string remaining, vector<string> &path, vector<vector<string>> &result) {\n        if (remaining.empty()) {\n            result.push_back(path);\n            return;\n        }\n        for (int i = 1; i <= remaining.size(); i++) {\n            string choice = remaining.substr(0, i);\n            if (!isPalindrome(choice)) continue;\n            path.push_back(choice);\n            backtrack(remaining.substr(i), path, result);\n            path.pop_back();\n        }\n    }\n};\n<\/code><\/pre>\n<\/div>\n\n<div class=\"wp_blog_code-tab-content\" data-lang=\"c\">\n<pre><code class=\"language-c\">\nbool isPalindrome(char *s, int start, int end) {\n    while (start < end) {\n        if (s[start++] != s[end--]) return false;\n    }\n    return true;\n}\nvoid backtrack(char *s, int start, char path[100][100], int pathLen) {\n    if (start == strlen(s)) {\n        printf(\"[\");\n        for (int i = 0; i < pathLen; i++) {\n            printf(\"\\\"%s\\\"\", path[i]);\n            if (i < pathLen - 1) printf(\", \");\n        }\n        printf(\"]\\n\");\n        return;\n    }\n    for (int i = start; i < strlen(s); i++) {\n        if (isPalindrome(s, start, i)) {\n            strncpy(path[pathLen], s + start, i - start + 1);\n            path[pathLen][i - start + 1] = '\\0';\n            backtrack(s, i + 1, path, pathLen + 1);\n        }\n    }\n}\nint main() {\n    char s[] = \"aab\";\n    char path[100][100];\n    backtrack(s, 0, path, 0);\n    return 0;\n}<\/code><\/pre>\n<\/div>\n\n<div class=\"wp_blog_code-tab-content\" data-lang=\"cs\">\n<pre><code class=\"language-csharp\">\nclass Solution {\n    public IList<IList<string>> Partition(string s) {\n        var result = new List<IList<string>>();\n        Backtrack(s, new List<string>(), result);\n        return result;\n    }\n\n    bool IsPalindrome(string s) {\n        int i = 0, j = s.Length - 1;\n        while (i < j) {\n            if (s[i++] != s[j--]) return false;\n        }\n        return true;\n    }\n    void Backtrack(string remaining, List<string> path, List<IList<string>> result) {\n        if (remaining.Length == 0) {\n            result.Add(new List<string>(path));\n            return;\n        }\n        for (int i = 1; i <= remaining.Length; i++) {\n            string choice = remaining.Substring(0, i);\n            if (!IsPalindrome(choice)) continue;\n            path.Add(choice);\n            Backtrack(remaining.Substring(i), path, result);\n            path.RemoveAt(path.Count - 1);\n        }\n    }\n}\n<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n\n<script>\ndocument.addEventListener(\"DOMContentLoaded\", () => {\n  const buttons = document.querySelectorAll(\".wp_blog_code-tab-button\");\n  const contents = document.querySelectorAll(\".wp_blog_code-tab-content\");\n\n  buttons.forEach((button) => {\n    button.addEventListener(\"click\", () => {\n      const lang = button.getAttribute(\"data-lang\");\n\n      buttons.forEach((btn) => btn.classList.remove(\"active\"));\n      contents.forEach((content) => content.classList.remove(\"active\"));\n\n      button.classList.add(\"active\");\n      document\n        .querySelector(`.wp_blog_code-tab-content[data-lang=\"${lang}\"]`)\n        .classList.add(\"active\");\n    });\n  });\n\n  const themeToggle = document.getElementById(\"blogNotesThemeToggle\");\n  const themeContainer = document.querySelector(\".wp_blog_theme\");\n\n  themeToggle.addEventListener(\"click\", () => {\n    themeContainer.classList.toggle(\"dark-mode\");\n    themeToggle.textContent =\n      themeContainer.classList.contains(\"dark-mode\") ? \"\u2600\ufe0f\" : \"\ud83c\udf19\";\n  });\n});\n<\/script>\n","protected":false},"excerpt":{"rendered":"<p>\ud83c\udf19 Problem Statement Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s. Example 1: Input: s = &#8220;aab&#8221; Output: [[&#8220;a&#8221;,&#8221;a&#8221;,&#8221;b&#8221;],[&#8220;aa&#8221;,&#8221;b&#8221;]] Example 2: Input: s = &#8220;a&#8221; Output: [[&#8220;a&#8221;]] Constraints 1 { if(!remainingString.length) { result.push([&#8230;path]); } for(let i=1; i<\/p>\n","protected":false},"author":108,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[210,322,260,176,175,211,811,810,174,172,173],"tags":[],"class_list":["post-9507","post","type-post","status-publish","format-standard","category-algorithms","category-algorithms-and-data-structures","category-c-c-plus-plus","category-csharp","category-cplusplus","category-data-structures","category-data-structures-and-algorithms","category-dsa","category-java","category-javascript","category-python"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/9507","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/users\/108"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=9507"}],"version-history":[{"count":2,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/9507\/revisions"}],"predecessor-version":[{"id":10255,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/9507\/revisions\/10255"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=9507"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=9507"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=9507"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}