38. Count and Say – Solution [Brute-Force to Best]

Here’s the question link on Leetcode 38. Count and Say:

https://leetcode.com/problems/count-and-say/description

Brute Force – Recursion O(n × L)

We can solve this recursively by generating the previous term first, then reading it to create the current term.

For every group of consecutive equal digits, count how many times it appears and append the count followed by the digit.

class Solution {
public:
    string countAndSay(int n) {
        if(n == 1) return "1";

        string prev = countAndSay(n - 1);
        string ans = "";

        for(int i = 0; i < prev.size(); ) {
            int j = i;

            while(j < prev.size() && prev[j] == prev[i]) {
                j++;
            }

            ans += to_string(j - i);
            ans += prev[i];

            i = j;
        }

        return ans;
    }
};
38. Count and Say Recursion

Optimal – Iterative Approach

We don’t actually need recursion here. We can simply start with "1" and keep generating the next term until we reach n.

The logic remains exactly the same: count consecutive digits and append the count followed by the digit.

class Solution {
public:
    string countAndSay(int n) {
        string ans = "1";

        for(int k = 2; k <= n; k++) {
            string temp = "";

            for(int i = 0; i < ans.size(); ) {
                int j = i;

                while(j < ans.size() && ans[j] == ans[i]) {
                    j++;
                }

                temp += to_string(j - i);
                temp += ans[i];

                i = j;
            }

            ans = temp;
        }

        return ans;
    }
};
38. Count and Say Iterative

Leave a Reply