Code Logo

Count and Say

Published at25 Jul 2026
Hard 0 views
Like0

The count-and-say sequence is a sequence of digit strings defined by the recursive formula: countAndSay(1) = "1". For n > 1, countAndSay(n) is the run-length encoding of countAndSay(n-1).

To generate the next term, read the previous term by counting consecutive identical digits: "1" is read as "one 1" → "11". "11" is read as "two 1s" → "21". "21" is read as "one 2, then one 1" → "1211".

Iterate n-1 times starting from "1". For each iteration, scan the current string counting consecutive equal digits and build the next string as count+digit.

Example Input & Output

Example 1
Input
1
Output
"1"
Explanation

Base case

Example 2
Input
4
Output
"1211"
Explanation

4th term of count-and-say

Example 3
Input
3
Output
"21"
Explanation

Third term

Example 4
Input
2
Output
"11"
Explanation

Second term

Example 5
Input
5
Output
"111221"
Explanation

Fifth term

Algorithm Flow

Recommendation Algorithm Flow for Count and Say
Recommendation Algorithm Flow for Count and Say

Solution Approach

function solution(n) {
  var s = '1';
  for (var i = 1; i < n; i++) {
    var next = '', count = 1;
    for (var j = 1; j <= s.length; j++) {
      if (j < s.length && s.charAt(j) === s.charAt(j - 1)) { count++; }
      else { next += count + s.charAt(j - 1); count = 1; }
    }
    s = next;
  }
  return s;
}

Best Answers

java
class Solution {
    public String solution(int n) {
        String s="1";
        for(int i=1;i<n;i++){StringBuilder nxt=new StringBuilder();int c=1;
            for(int j=1;j<=s.length();j++){
                if(j<s.length()&&s.charAt(j)==s.charAt(j-1))c++;
                else{nxt.append(c).append(s.charAt(j-1));c=1;}
            }s=nxt.toString();
        }return s;
    }
}