{"id":12208,"date":"2026-04-15T23:18:00","date_gmt":"2026-04-15T17:48:00","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=12208"},"modified":"2026-04-15T23:20:27","modified_gmt":"2026-04-15T17:50:27","slug":"count-and-say","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/count-and-say\/","title":{"rendered":"Count and Say"},"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            The count-and-say sequence is a sequence of digit strings defined by the recursive formula:\n        <ul>\n            <li><code>countAndSay(1) = \"1\"<\/code><\/li>\n            <li><code>countAndSay(n)<\/code> is the run-length encoding of <code>countAndSay(n - 1)<\/code>.<\/li>\n        <\/ul>\n        \n        <\/p>\n        <p>Run-length encoding (RLE) is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string <code>\"3322251\"<\/code> we replace <code>\"33\"<\/code> with <code>\"23\"<\/code>, replace <code>\"222\"<\/code> with <code>\"32\"<\/code>, replace <code>\"5\"<\/code> with <code>\"15\"<\/code> and replace <code>\"1\"<\/code> with <code>\"11\"<\/code>. Thus the compressed string becomes <code>\"23321511\"<\/code>.<\/p>\n        \n        <p>Given a positive integer <i>n<\/i>, return the <code>n<sup>th<\/sup><\/code> <i>element of the <strong>count-and-say sequence<\/strong><\/i>.<\/p>\n        \n\n\n                <h2>Examples:<\/h2>\n\n                <h3>Example 1:<\/h3>\n                <p><strong>Input:<\/strong> n = 4\n                <\/p>\n                <p><strong>Output:<\/strong> &#8220;1211&#8221;<\/p>\n                <p>\n                  <code>Explanation:<\/code>\n                    <ul>\n                       <li>countAndSay(1) = &#8220;1&#8221;<\/li>\n                       <li>countAndSay(2) = RLE of &#8220;1&#8221; = &#8220;11&#8221;<\/li>\n                       <li>countAndSay(3) = RLE of &#8220;11&#8221; = &#8220;21&#8221;<\/li>\n                       <li>countAndSay(4) = RLE of &#8220;21&#8221; = &#8220;1211&#8221;<\/li>\n                    <\/ul>\n                <\/p>\n\n\n                <h3>Example 2:<\/h3>\n                <p><strong>Input:<\/strong> n = 1<\/p>\n\n                <p><strong>Output:<\/strong> &#8220;1&#8221;<\/p>\n                <p><strong>Explanation:<\/strong> This is the base case.<\/p>\n\n                <!-- <h3>Example 3:<\/h3>\n                <p><strong>Input:<\/strong> s = \"2[abc]3[cd]ef\"<\/p>\n\n                <p><strong>Output:<\/strong> \"abcabccdcdcdef\"<\/p> \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>countAndSay(3) = RLE of \"11\" = \"21\"<\/code><\/p>\n\n                    <h2>Time Complexity:<\/h2>\n                    <li>\n                      <p><strong>Time Complexity = O(n x m)<\/strong>\n                        where <code>m<\/code> is length of the generated string at each step.\n                      <\/li>\n                    <h2>Space Complexity:<\/h2>\n                    <li>\n                      <p><strong>Space Complexity = O(m)<\/strong><\/p>\n                    <\/li>\n\n<h2>Approach<\/h2>\n<ul>\n    <li><strong>For every iteration from 2 to n:<\/strong>\n    <ul>\n        <li>Initialize an empty string <code>rle<\/code> to store the next <strong>sequence<\/strong>.<\/li>\n        <li><strong>Traverse the current<\/strong> string curr and keep a count of <code>repeating characters<\/code>.<\/li>\n        <li>If the <code>current character<\/code> is the same as the previous one, <strong>increment the count<\/strong>.<\/li>\n        <li>Otherwise:\n            <ul>\n                <li><code>Append the count<\/code> and the previous character to <strong>rle<\/strong>.<\/li>\n                <li><strong>Reset<\/strong> <code>count to 1<\/code> for the new character.<\/li>\n            <\/ul>\n        <\/li>\n    <\/ul>\n    <\/li>\n    <li>After the <code>loop<\/code>, <strong>update curr<\/strong> with the newly formed <code>rle<\/code>.<\/li>\n    <li>This process continues until we reach the <code>n-th term<\/code>.<\/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>n = 4<\/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   curr = \"1\"\n\ni = 2:\n   curr = \"1\"\n   rle = \"\"\n   count = 1\n\n   j = 1:\n      curr[1] != curr[0]  (undefined != '1')\n      rle = \"\" + \"1\" + \"1\" = \"11\"\n      count = 1\n\n   curr = \"11\"\n\ni = 3:\n   curr = \"11\"\n   rle = \"\"\n   count = 1\n\n   j = 1:\n      curr[1] == curr[0] ('1' == '1')\n      count = 2\n\n   j = 2:\n      curr[2] != curr[1] (undefined != '1')\n      rle = \"\" + \"2\" + \"1\" = \"21\"\n      count = 1\n\n   curr = \"21\"\n\ni = 4:\n   curr = \"21\"\n   rle = \"\"\n   count = 1\n\n   j = 1:\n      curr[1] != curr[0] ('1' != '2')\n      rle = \"\" + \"1\" + \"2\" = \"12\"\n      count = 1\n\n   j = 2:\n      curr[2] != curr[1] (undefined != '1')\n      rle = \"12\" + \"1\" + \"1\" = \"1211\"\n      count = 1\n\n   curr = \"1211\"\n\nFinal:\n   return \"1211\"\n  <\/pre> \n  \n  <p><strong>Output:<\/strong> <code>\"1211\"<\/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 countAndSay = function(n) {\n\n    let curr = \"1\";\n    for(let i = 2; i <= n; i++) {\n\n    let rle = \"\";\n    let count = 1;\n\n    for(let j = 1; j <= curr.length; j++) { \n        if(curr[j] === curr[j - 1]) {\n            ++count; \n        }else { \n            rle = rle + count + curr[j - 1]; \n            count = 1; \n        } \n    } \n      curr = rle; \n    } \n    \n    return curr;\n};\n    <\/code><\/pre>\n    <\/div>\n    <div class=\"wp_blog_code-tab-content\" data-lang=\"py\">\n        <pre><code class=\"language-python\">\ndef countAndSay(n):\n    curr = \"1\"\n\n    for i in range(2, n + 1):\n        rle = \"\"\n        count = 1\n\n        for j in range(1, len(curr) + 1):\n            if j < len(curr) and curr[j] == curr[j - 1]:\n                count += 1\n            else:\n                rle += str(count) + curr[j - 1]\n                count = 1\n\n        curr = rle\n\n    return curr\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    public String countAndSay(int n) {\n        String curr = \"1\";\n\n        for (int i = 2; i <= n; i++) {\n            StringBuilder rle = new StringBuilder();\n            int count = 1;\n\n            for (int j = 1; j <= curr.length(); j++) {\n                if (j < curr.length() &#038;&#038; curr.charAt(j) == curr.charAt(j - 1)) {\n                    count++;\n                } else {\n                    rle.append(count).append(curr.charAt(j - 1));\n                    count = 1;\n                }\n            }\n\n            curr = rle.toString();\n        }\n\n        return curr;\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    string countAndSay(int n) {\n        string curr = \"1\";\n\n        for (int i = 2; i <= n; i++) {\n            string rle = \"\";\n            int count = 1;\n\n            for (int j = 1; j <= curr.length(); j++) {\n                if (j < curr.length() &#038;&#038; curr[j] == curr[j - 1]) {\n                    count++;\n                } else {\n                    rle += to_string(count) + curr[j - 1];\n                    count = 1;\n                }\n            }\n\n            curr = rle;\n        }\n\n        return curr;\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\nchar* countAndSay(int n) {\n    char* curr = (char*)malloc(2);\n    strcpy(curr, \"1\");\n\n    for (int i = 2; i <= n; i++) {\n        int len = strlen(curr);\n        char* rle = (char*)malloc(len * 2 + 1);\n        int index = 0, count = 1;\n\n        for (int j = 1; j <= len; j++) {\n            if (j < len &#038;&#038; curr[j] == curr[j - 1]) {\n                count++;\n            } else {\n                index += sprintf(rle + index, \"%d%c\", count, curr[j - 1]);\n                count = 1;\n            }\n        }\n\n        free(curr);\n        curr = rle;\n    }\n\n    return curr;\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    public string CountAndSay(int n) {\n        string curr = \"1\";\n\n        for (int i = 2; i <= n; i++) {\n            string rle = \"\";\n            int count = 1;\n\n            for (int j = 1; j <= curr.Length; j++) {\n                if (j < curr.Length &#038;&#038; curr[j] == curr[j - 1]) {\n                    count++;\n                } else {\n                    rle += count.ToString() + curr[j - 1];\n                    count = 1;\n                }\n            }\n\n            curr = rle;\n        }\n\n        return curr;\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","protected":false},"excerpt":{"rendered":"<p>\ud83c\udf19 Problem Statement: The count-and-say sequence is a sequence of digit strings defined by the recursive formula: countAndSay(1) = &#8220;1&#8221; countAndSay(n) is the run-length encoding of countAndSay(n &#8211; 1). Run-length encoding (RLE) is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character<\/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-12208","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\/12208","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=12208"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/12208\/revisions"}],"predecessor-version":[{"id":12209,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/12208\/revisions\/12209"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=12208"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=12208"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=12208"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}