{"id":12206,"date":"2026-04-15T22:57:02","date_gmt":"2026-04-15T17:27:02","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=12206"},"modified":"2026-04-15T23:19:11","modified_gmt":"2026-04-15T17:49:11","slug":"decode-string","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/decode-string\/","title":{"rendered":"Decode String"},"content":{"rendered":"\n\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    <div class=\"wp_blog_explanation\">\n        <h2>Problem Statement:<\/h2>\n        <p>\n            Given an encoded string, return its decoded string.\n        <\/p>\n        <p>\n            The encoding rule is: <code>k[encoded_string]<\/code>, where the <code>encoded_string<\/code> inside the square brackets is being repeated exactly <code>k<\/code> times. Note that <code>k<\/code> is guaranteed to be a positive integer.\n        <\/p>\n        <p>\n            You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, <code>k<\/code>. For example, there will not be input like <code>3a<\/code> or <code>2[4]<\/code>.\n        <\/p>\n\n        <p>\n            The test cases are generated so that the length of the output will never exceed <code>10<sup>5<\/sup><\/code>.\n        <\/p>\n\n                <h2>Examples:<\/h2>\n\n                <h3>Example 1:<\/h3>\n                <p><strong>Input:<\/strong> s = &#8220;3[a]2[bc]&#8221;\n                <\/p>\n                <p><strong>Output:<\/strong> &#8220;aaabcbc&#8221;<\/p>\n                <!-- <p>\n                  <code>Explanation:<\/code>\n                  The substrings with non-zero beauty are [\"aab\",\"aabc\",\"aabcb\",\"abcb\",\"bcb\"], each with beauty equal to 1.\n                <\/p> -->\n\n\n                <h3>Example 2:<\/h3>\n                <p><strong>Input:<\/strong> s = &#8220;3[a2[c]]&#8221;<\/p>\n\n                <p><strong>Output:<\/strong> &#8220;accaccacc&#8221;<\/p>\n                <!-- <p><strong>Explanation:<\/strong> Your reversed string should not contain leading or trailing spaces.<\/p> -->\n\n                <h3>Example 3:<\/h3>\n                <p><strong>Input:<\/strong> s = &#8220;2[abc]3[cd]ef&#8221;<\/p>\n\n                <p><strong>Output:<\/strong> &#8220;abcabccdcdcdef&#8221;<\/p> \n                <!-- <p><strong>Explanation:<\/strong> You need to reduce multiple spaces between two words to a single space in the reversed string.<\/p> --> \n        \n\n                <!-- <h5>Example 3:<\/h5>\n                <p><strong>Input:<\/strong>\n                <\/p>\n                <p>\n                    nums1 = [0], m = 0\n                    nums2 = [1], n = 1\n                <\/p>    \n                <p><strong>Output:<\/strong>[1]<\/p>\n                  <p>\n                  <code>Explanation:<\/code>\n                 The arrays we are merging are [] and [1].\n                    The result of the merge is [1].\n                    Note that because m = 0, there are no elements in nums1. \n                    The 0 is only there to ensure the merge result can fit in nums1.\n                <\/p> -->\n\n                <h2>Constraints<\/h2>\n                <p><code>1 <= s.length <= 30<\/code><\/p>\n                <p><code>\n                  <code>s<\/code> consists of lowercase English letters, digits, and square brackets <code>'[]'<\/code>.\n                <\/code><\/p>\n                <p><code>s<\/code> is guaranteed to be a valid input.<\/p>\n                <p>All the integers in <code>s<\/code> are in the range <code>[1, 300]<\/code>.<\/p>\n\n                    <h2>Time Complexity:<\/h2>\n                    <li>\n                      <p><strong>Time Complexity = O(n x k)<\/strong>\n                        where <code>n<\/code> is length of string and <code>k<\/code> is max repetition.\n                      <\/li>\n                    <h2>Space Complexity:<\/h2>\n                    <li>\n                      <p><strong>Space Complexity = O(n)<\/strong><\/p>\n                    <\/li>\n\n<h2>Approach<\/h2>\n<ul>\n    <li>Use recursion to handle nested patterns like <code>k[encoded_string]<\/code>.<\/li>\n    <li>Maintain a global pointer (<code>i<\/code>) to traverse the string.<\/li>\n    <li><strong>For each character<\/strong>:\n        <ul>\n            <li>If it is a digit, build the number <code>k<\/code> (to handle multi-digit values).<\/li>\n            <li>If you encounter <code>\"[\"<\/code>, recursively decode the <strong>substring<\/strong> inside the brackets.<\/li>\n            <li>Repeat the decoded substring <code>k<\/code> times and append it to the <strong>result<\/strong>.<\/li>\n            <li>If you encounter <code>\"]\"<\/code>, <strong>return the current built string<\/strong> (end of current recursion level).<\/li>\n            <li>If it is a <strong>character<\/strong>, directly append it to the <code>result<\/code>.<\/li>\n        <\/ul>\n    <\/li>\n<\/ul>\n\n<h2>Dry Run<\/h2>\n<div style=\"background: var(--light-bg); border-left: 4px solid var(--primary); padding: 1rem; border-radius: var(--tab-radius); margin: 1rem 0; color: var(--text-dark);\"> \n  <p><strong>Input:<\/strong> <code>s = \"3[a2[c]]\"<\/code><\/p> \n  \n  <pre style=\"white-space: pre-wrap; background: var(--code-bg); padding: 1rem; border-radius: 8px; overflow-x: auto; color: var(--code-text);\">\nInitial:\n   i = 0\n\nCall decode():\n   res = \"\"\n   num = 0\n\ni = 0 \u2192 char = '3'\n   num = 3\n   i = 1\n\ni = 1 \u2192 char = '['\n   i = 2\n   Call decode():\n\n      res = \"\"\n      num = 0\n\n      i = 2 \u2192 char = 'a'\n         res = \"a\"\n         i = 3\n\n      i = 3 \u2192 char = '2'\n         num = 2\n         i = 4\n\n      i = 4 \u2192 char = '['\n         i = 5\n         Call decode():\n\n            res = \"\"\n            num = 0\n\n            i = 5 \u2192 char = 'c'\n               res = \"c\"\n               i = 6\n\n            i = 6 \u2192 char = ']'\n               i = 7\n               return \"c\"\n\n         Back to previous call:\n         str = \"c\"\n         res = \"a\" + \"c\".repeat(2) = \"acc\"\n         num = 0\n\n      i = 7 \u2192 char = ']'\n         i = 8\n         return \"acc\"\n\n   Back to main call:\n   str = \"acc\"\n   res = \"\" + \"acc\".repeat(3) = \"accaccacc\"\n   num = 0\n\ni = 8 \u2192 end of string\n\nFinal:\n   return \"accaccacc\"\n  <\/pre> \n  \n  <p><strong>Output:<\/strong> <code>\"accaccacc\"<\/code><\/p> \n<\/div>\n<\/div>\n\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\">\n            JavaScript\n        <\/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 decodeString = function(s) {\n    let i = 0;\n\n    let decode = () => {\n        let res = \"\";\n        let num = 0;\n\n        while (i < s.length) {\n            let char = s[i];\n\n            if (char >= '0' && char <= '9') {\n                num = num * 10 + parseInt(char);\n                i++;\n            } \n            else if (char === \"[\") {\n                i++;\n                let str = decode();\n                res += str.repeat(num);\n                num = 0;\n            } \n            else if (char === \"]\") {\n                i++;\n                return res;\n            } \n            else {\n                res += char;\n                i++;\n            }\n        }\n\n        return res;\n    };\n\n    return decode();\n};\n    <\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"py\">\n        <pre><code class=\"language-python\">\ndef decodeString(s: str) -> str:\n    i = 0\n\n    def decode():\n        nonlocal i\n        res = \"\"\n        num = 0\n\n        while i < len(s):\n            char = s[i]\n\n            if char.isdigit():\n                num = num * 10 + int(char)\n                i += 1\n\n            elif char == '[':\n                i += 1\n                decoded = decode()\n                res += decoded * num\n                num = 0\n\n            elif char == ']':\n                i += 1\n                return res\n\n            else:\n                res += char\n                i += 1\n\n        return res\n\n    return decode()\n    <\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"java\">\n        <pre><code class=\"language-java\">\nclass Solution {\n    int i = 0;\n\n    public String decodeString(String s) {\n        return decode(s);\n    }\n\n    private String decode(String s) {\n        StringBuilder res = new StringBuilder();\n        int num = 0;\n\n        while (i < s.length()) {\n            char ch = s.charAt(i);\n\n            if (Character.isDigit(ch)) {\n                num = num * 10 + (ch - '0');\n                i++;\n            } \n            else if (ch == '[') {\n                i++;\n                String decoded = decode(s);\n                for (int k = 0; k < num; k++) {\n                    res.append(decoded);\n                }\n                num = 0;\n            } \n            else if (ch == ']') {\n                i++;\n                return res.toString();\n            } \n            else {\n                res.append(ch);\n                i++;\n            }\n        }\n\n        return res.toString();\n    }\n}\n<\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"cpp\">\n        <pre><code class=\"language-cpp\">\nclass Solution {\npublic:\n    int i = 0;\n\n    string decodeString(string s) {\n        return decode(s);\n    }\n\n    string decode(string &s) {\n        string res = \"\";\n        int num = 0;\n\n        while (i < s.length()) {\n            char ch = s[i];\n\n            if (isdigit(ch)) {\n                num = num * 10 + (ch - '0');\n                i++;\n            } \n            else if (ch == '[') {\n                i++;\n                string decoded = decode(s);\n                while (num--) res += decoded;\n                num = 0;\n            } \n            else if (ch == ']') {\n                i++;\n                return res;\n            } \n            else {\n                res += ch;\n                i++;\n            }\n        }\n\n        return res;\n    }\n};\n    <\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"c\">\n        <pre><code class=\"language-c\">\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n#include &lt;ctype.h&gt;\n\nchar* decode(char* s, int* i);\n\nchar* decodeString(char* s) {\n    int i = 0;\n    return decode(s, &i);\n}\n\nchar* decode(char* s, int* i) {\n    char* res = (char*)malloc(10000); \/\/ assume max size\n    res[0] = '\\0';\n    int num = 0;\n\n    while (s[*i] != '\\0') {\n        char ch = s[*i];\n\n        if (isdigit(ch)) {\n            num = num * 10 + (ch - '0');\n            (*i)++;\n        } \n        else if (ch == '[') {\n            (*i)++;\n            char* decoded = decode(s, i);\n\n            for (int k = 0; k < num; k++) {\n                strcat(res, decoded);\n            }\n            num = 0;\n            free(decoded);\n        } \n        else if (ch == ']') {\n            (*i)++;\n            return res;\n        } \n        else {\n            int len = strlen(res);\n            res[len] = ch;\n            res[len + 1] = '\\0';\n            (*i)++;\n        }\n    }\n\n    return res;\n}\n   <\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"cs\">\n        <pre><code class=\"language-csharp\">\npublic class Solution {\n    int i = 0;\n\n    public string DecodeString(string s) {\n        return Decode(s);\n    }\n\n    private string Decode(string s) {\n        string res = \"\";\n        int num = 0;\n\n        while (i < s.Length) {\n            char ch = s[i];\n\n            if (char.IsDigit(ch)) {\n                num = num * 10 + (ch - '0');\n                i++;\n            } \n            else if (ch == '[') {\n                i++;\n                string decoded = Decode(s);\n                for (int k = 0; k < num; k++) {\n                    res += decoded;\n                }\n                num = 0;\n            } \n            else if (ch == ']') {\n                i++;\n                return res;\n            } \n            else {\n                res += ch;\n                i++;\n            }\n        }\n\n        return res;\n    }\n}\n  <\/code><\/pre>\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\n\n","protected":false},"excerpt":{"rendered":"<p>\ud83c\udf19 Problem Statement: Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. You may assume that the input string is always valid; there are no extra white spaces,<\/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-12206","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\/12206","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=12206"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/12206\/revisions"}],"predecessor-version":[{"id":12207,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/12206\/revisions\/12207"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=12206"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=12206"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=12206"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}