Tutorialspoint
Problem
Solution
Submissions

Count and Say Sequence

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a C program to generate the nth term of the "Count and Say" sequence. 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, followed by the digit. Finally, concatenate every said digit.

For example, the saying and conversion for digit string "3322251":
Two 3's, three 2's, one 5, and one 1 becomes "23321511".

Example 1
  • Input: n = 1
  • Output: "1"
  • Explanation:
    Step 1: countAndSay(1) = "1" (base case)
Example 2
  • Input: n = 4
  • Output: "1211"
  • Explanation:
    Step 1: countAndSay(1) = "1" (base case)
    Step 2: countAndSay(2) = say "1" = one 1 = "11"
    Step 3: countAndSay(3) = say "11" = two 1's = "21"
    Step 4: countAndSay(4) = say "21" = one 2 followed by one 1 = "1211"
Constraints
  • 1 ≤ n ≤ 30
  • The answer string will only contain digits
  • Time Complexity: O(2^n) - since the length of the result can grow exponentially
  • Space Complexity: O(2^n) - to store the result string
NumberControl StructureseBayD. E. Shaw
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a recursive approach or an iterative approach to generate the sequence
  • For each iteration, generate the next term by reading the previous term
  • Use two pointers or a counter to track consecutive identical digits
  • Build the result string by concatenating the count and the digit
  • Handle the base case separately (when n = 1)

Steps to solve by this approach:

 Step 1: Start with the base case string "1" for n = 1.

 Step 2: For each iteration from 2 to n, generate the next term by reading the previous term.
 Step 3: Use a counter to track consecutive identical digits.
 Step 4: For each digit in the previous term, check if it matches the next digit.
 Step 5: If it matches, increment the counter; otherwise, append the count and the digit to the result.
 Step 6: Update the previous term with the newly generated term.
 Step 7: Return the final string after n-1 iterations.

Submitted Code :