Count and Say
Medium
Topics
The count-and-say sequence starts at "1". Each later term is produced by reading the previous one aloud: split it into runs of the same digit, and write each run as its length followed by the digit.
So "3322251" reads as two 3s, three 2s, one 5, one 1, giving "23" + "32" + "15" + "11" = "23321511".
Return the n-th term, counting from 1.
Example 1
1, reached by reading each term aloud to get the next. Reading means splitting into runs of the same digit and writing each run as its length then its digit. The first term is given rather than derived, so there is nothing to read yet.Input: n = 1 Output: "1" Explanation: The first term is given.
Example 2
Input: n = 4 Output: "1211" Explanation: The sequence runs 1, then 11, then 21, then 1211.
Example 3
Input: n = 6 Output: "312211" Explanation: After 1211 comes 111221, then 312211.
Constraints
- 1 <= n <= 30
Editorial — intuition, approach, complexity and pitfalls
Intuition
There is no shortcut: term n is defined in terms of term n - 1, so the only way to it is to build each term in turn from "1".
The step itself is a run-length encoding. Walk the string, and whenever the digit changes, write out how many of the previous digit you just passed and then that digit. The usual bug is forgetting the final run, because the loop ends without a change to trigger the write.
The clean way to avoid that is to handle the current run inside the loop and flush once more after it ends, or to compare against the next character rather than the previous one and treat the end of the string as a change.
Two things worth noticing about the output. It describes digits, not values, so a run of eleven 1s is written "111" — count 11 followed by digit 1 — and not anything else. And the terms grow quickly, which is why n is capped at 30.
Approach
- Start with
"1". - Repeat
n - 1times: build the next term from the current one. - To build it, walk the current term tracking the digit of the run you are in and how long it is.
- When the digit changes, append the run length and then the run digit, and start a new run.
- After the walk, append the final run — the step most often missed.
- Return the term after the last round.
Walkthrough
n = 6
term 1: "1"
term 2: read "1"
one 1 -> "11"
term 3: read "11"
two 1s -> "21"
term 4: read "21"
one 2, one 1 -> "12" + "11" = "1211"
term 5: read "1211"
one 1 -> "11"
one 2 -> "12"
two 1s -> "21"
-> "111221"
term 6: read "111221"
three 1s -> "31"
two 2s -> "22"
one 1 -> "11"
-> "312211"
answer "312211"
the run that gets dropped
reading "111221", the final run is the single trailing 1.
A loop that only writes when the digit CHANGES never
writes it, and the answer comes out "3122" instead.Complexity
- Time — O(n * L): each of the n rounds scans the current term, whose length L grows with n.
- Space — O(L): the current term and the one being built.
Common Pitfalls
- Dropping the last run, which is the single most common mistake here.
- Writing the digit before the count. It is length first, then digit.
- Running the loop
ntimes instead ofn - 1, which returns the term after the one asked for. - Treating the term as a number rather than a string of digits. The terms outgrow any integer type well before
n = 30. - Trying to find a formula. Each term genuinely depends on the previous one.
Full Solution — all languages
class Solution:
def countAndSay(self, n):
term = "1"
for _ in range(n - 1):
out = []
digit = term[0]
run = 0
for ch in term:
if ch == digit:
run += 1
else:
out.append(str(run))
out.append(digit)
digit = ch
run = 1
# The final run has no change to trigger it inside the loop.
out.append(str(run))
out.append(digit)
term = "".join(out)
return termimport java.util.*;
class Solution {
public String countAndSay(int n) {
String term = "1";
for (int round = 1; round < n; round++) {
StringBuilder out = new StringBuilder();
char digit = term.charAt(0);
int run = 0;
for (int i = 0; i < term.length(); i++) {
char ch = term.charAt(i);
if (ch == digit) run++;
else {
out.append(run).append(digit);
digit = ch;
run = 1;
}
}
out.append(run).append(digit);
term = out.toString();
}
return term;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: string countAndSay(int n) {
string term = "1";
for (int round = 1; round < n; round++) {
string out;
char digit = term[0];
int run = 0;
for (char ch : term) {
if (ch == digit) run++;
else {
out += to_string(run);
out += digit;
digit = ch;
run = 1;
}
}
out += to_string(run);
out += digit;
term = out;
}
return term;
}
};/**
* @param {number} n
* @return {string}
*/ var countAndSay = function(n) {
let term = "1";
for (let round = 1; round < n; round++) {
let out = "";
let digit = term[0], run = 0;
for (const ch of term) {
if (ch === digit) run++;
else {
out += String(run) + digit;
digit = ch;
run = 1;
}
}
out += String(run) + digit;
term = out;
}
return term;
};