Skip to content

Link to Question

MEDIUM

Count and Say

The count-and-say sequence is a sequence of digit strings defined by the recursive formula:

  • countAndSay(1) = "1"
  • countAndSay(n) is the way you would "say" the digit string from countAndSay(n-1), which is then converted into a different digit string.

To determine how you "say" a digit string, split it into the minimal number of substrings such that each substring contains exactly one unique digit. Then for each substring, say the number of digits, then say the digit. Concatenate every said pair to get the next sequence.

Example

Input:

n = 4

Output:

"1211"

Explanation:
countAndSay(1) = "1" countAndSay(2) = say "1" = one 1 = "11" countAndSay(3) = say "11" = two 1's = "21" countAndSay(4) = say "21" = one 2 + one 1 = "1211"


Constraints

  • 1 ≤ n ≤ 30

Solution: Iterative

  • Time Complexity: O(n * m), where m is the length of the result string at each step.
  • Space Complexity: O(m)
C++
class Solution {
public:
    string countAndSay(int n) {
        string res = "1";
        for (int i = 1; i < n; ++i) {
            string cur;
            for (int j = 0; j < res.size(); ) {
                int k = j;
                while (k < res.size() && res[k] == res[j]) ++k;
                cur += to_string(k - j) + res[j];
                j = k;
            }
            res = cur;
        }
        return res;
    }
};