medium Count and Say
Problem Statement
Given an integer n greater than 0, return the nth count-and-say sequence.
A count-and-say sequence is a string of digits created using specific rules given below.
countAndSay(1) = "1"countAndSay(2) = say countAndSay(1)countAndSay(n) = say countAndSay(n - 1)
You start with "1", and for each subsequent string, you "read off" the digits of the previous string, counting the number of digits in groups of the same digit.
- For instance,
say "1223"is read off asone 1 + two 2 + one 3or112213.
Examples
-
Example 1:
- Input:
n = 3 - Expected Output:
"21" - Justification: The sequence is "1", "11" (one 1), "21" (two 1s).
- Input:
-
Example 2:
- Input:
n = 4 - Expected Output:
"1211" - Justification: Continuing from the last example, "21" is read as "one 2 + one 1" or "1211".
- Input:
-
Example 3:
- Input:
n = 5 - Expected Output:
"111221" - Justification: Continuing from the last example, "1211" is read as "one 1 + one 2 + two 1s" or "111221".
- Input:
Try it yourself
Try solving this question here:
✅ Solution Count and Say
Problem Statement
Given an integer n greater than 0, return the nth count-and-say sequence.
A count-and-say sequence is a string of digits created using specific rules given below.
countAndSay(1) = "1"countAndSay(2) = say countAndSay(1)countAndSay(n) = say countAndSay(n - 1)
You start with "1", and for each subsequent string, you "read off" the digits of the previous string, counting the number of digits in groups of the same digit.
- For instance,
say "1223"is read off asone 1 + two 2 + one 3or112213.
Examples
-
Example 1:
- Input:
n = 3 - Expected Output:
"21" - Justification: The sequence is "1", "11" (one 1), "21" (two 1s).
- Input:
-
Example 2:
- Input:
n = 4 - Expected Output:
"1211" - Justification: Continuing from the last example, "21" is read as "one 2 + one 1" or "1211".
- Input:
-
Example 3:
- Input:
n = 5 - Expected Output:
"111221" - Justification: Continuing from the last example, "1211" is read as "one 1 + one 2 + two 1s" or "111221".
- Input:
Solution
To solve this problem, we employ a recursive or iterative approach to build each string in the sequence from its predecessor. Initially, the sequence starts with "1". For each subsequent string, we iterate through the previous string, keeping track of the current digit and the count of its consecutive occurrences. When the current digit changes, we append its count and value to the new string. This process effectively 'counts and says' the digits of the previous string. This approach works because each string in the sequence is constructed by describing the composition of the previous string, ensuring the correctness and continuation of the sequence.
Step-by-step Algorithm
-
Initialization:
- Define a string variable
resultand initialize it to"1", representing the base case of the sequence. This variable will hold the current term in the sequence.
- Define a string variable
-
Outer Loop - Sequence Construction:
- Iterate from
2ton(inclusive) using a loop variable, sayi. This loop is used to construct each term in the sequence, up to thenth term.
- Iterate from
-
Inner Loop - Term Construction:
- Inside the outer loop, initialize a new empty string
currentto build theith term of the sequence. - Set two variables,
countandprev. Initializecountto1(to count the occurrences of a digit) andprevto the first character ofresult(to track the current digit being counted).
- Inside the outer loop, initialize a new empty string
-
Counting and Saying:
- Iterate through each character of the
resultstring using a loop variable, sayj. - If the current character (
result[j]) is the same asprev, incrementcount. - If it's different, append the value of
countfollowed byprevto thecurrentstring. This is the "say" part. Resetcountto1and updateprevto the current character (result[j]).
- Iterate through each character of the
-
Finalizing the Current Term:
- After the inner loop, append the last counted
countandprevvalues to thecurrentstring. This step is necessary to include the count of the last sequence of digits.
- After the inner loop, append the last counted
-
Update for Next Iteration:
- Update the
resultstring with the newly constructedcurrentstring. This makesresultready for the next iteration.
- Update the
-
Returning the Result:
- After the outer loop completes, return the
resultstring, which now contains thenth term of the sequence.
- After the outer loop completes, return the
Algorithm Walkthrough
Let's consider the input: 5.
-
Initialization
result = "1". This is the base term of the sequence.
-
1st Iteration (i = 2)
- Create
currentto build the next term. - Set
count = 1(initial count of digits) andprev = '1'(the first character ofresult). - Iterate through
result:- Only one character '1', so
current = "11"(one 1).
- Only one character '1', so
- Create
-
2nd Iteration (i = 3)
- Update
result = "11". - Reset
current,count = 1,prev = '1'. - Iterate through
result:- Two consecutive '1's, so
current = "21"(two 1s).
- Two consecutive '1's, so
- Update
-
3rd Iteration (i = 4)
- Update
result = "21". - Reset
current,count = 1,prev = '2'. - Iterate through
result:- one '2', so
current = "12", then another '1', socurrent = "1211"(one 2, one 1).
- one '2', so
- Update
-
4th Iteration (i = 5)
- Update
result = "1211". - Reset
current,count = 1,prev = '1'. - Iterate through
result:- One '1', so
current = "11", then one '2', socurrent = "1112", then two '1's, socurrent = "111221"(one 1, one 2, two 1s).
- One '1', so
- Update
-
End of Iterations:
- Update
result = "111221".
- Update
-
Output
- The 5th term in the sequence is
"111221".
- The 5th term in the sequence is
The final output for input 5 is "111221", which is the 5th term in the "Count and Say" sequence.
Code
public class Solution {
public String countAndSay(int n) {
// Base string for the sequence
String result = "1";
// Building each string in the sequence
for (int i = 2; i <= n; i++) {
StringBuilder current = new StringBuilder();
int count = 1;
char prev = result.charAt(0);
// Iterating over the string
for (int j = 1; j < result.length(); j++) {
if (result.charAt(j) == prev) {
count++;
} else {
// Appending the count and previous character
current.append(count).append(prev);
prev = result.charAt(j);
count = 1;
}
}
// Appending the last counted character
current.append(count).append(prev);
result = current.toString();
}
return result;
}
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.countAndSay(3)); // "21"
System.out.println(solution.countAndSay(4)); // "1211"
System.out.println(solution.countAndSay(5)); // "111221"
}
}
Complexity Analysis
Time Complexity
The time complexity is primarily determined by two factors: The number of iterations (up to n) and the length of the sequence at each iteration (which grows). The length of each sequence term increases at each step, and although it doesn't strictly double, it grows rapidly.
Therefore, the total time complexity can be approximated as O(n * L(n)), where L(n) is the length of the sequence at step n. This growth is super-linear but not strictly exponential.
Space Complexity
The space complexity is driven by the space needed to store the current and previous sequence strings. At any step, the space required is proportional to the length of the longest sequence, which is the sequence at step n. Therefore, the space complexity can be approximated as O(L(n)), where L(n) is the length of the sequence at step n.
🤖 Don't fully get this? Learn it with Claude
Stuck on Count and Say? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Count and Say** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Count and Say** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Count and Say**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Count and Say**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.