The count-and-say sequence is a series of strings where each term describes the previous term using run-length encoding. Starting with "1", each subsequent term reads the previous term by counting consecutive identical digits.
For example: 1 is read as "one 1" → "11". "11" is read as "two 1s" → "21". "21" is read as "one 2, one 1" → "1211". Given n (1-indexed), return the nth term of the sequence.
This problem teaches run-length encoding and iterative sequence generation. It tests your ability to build a string by counting consecutive identical characters and appending the count followed by the character.
The solution starts with "1" and iterates n-1 times. For each iteration, traverse the current string, count consecutive identical digits, and build the next string by appending each count followed by the digit.
Edge cases include n = 1 (return "1"), large n where the string grows exponentially, and ensuring the count is always correct even when digits repeat many times.
Example Input & Output
Base case
4th term of count-and-say
Third term
Second term
Fifth term
Algorithm Flow
Solution Approach
Build the sequence iteratively by counting consecutive identical digits using run-length encoding.
Start with "1". Repeat n-1 times: traverse the current string, counting consecutive same digits. When a change is detected, append the count and the previous digit. After the loop, append the last group. Update result for the next iteration.
Time complexity is O(2^n) in the worst case as the string length grows exponentially. Space complexity is O(2^n) for the result.
Best Answers
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;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
