Pinterest
Count and Say
Codingmedium
Problem
The count-and-say sequence is built one term at a time, starting from the seed term "1". Every later term is produced by scanning the previous term from left to right and, for each run of identical consecutive digits, writing down how many times that digit repeats followed by the digit itself.
Given an integer n, return the n-th term of this sequence as a string.
Rules to keep in mind:
- The sequence is 1-indexed: the 1st term is
"1". - Each term is generated purely from the digits of the term before it — never skip a step, even though you only need to return the final one.
- A "run" means maximal consecutive repeats of the same digit; adjacent runs of different digits are always described separately, even if they'd produce ambiguous-looking output.
Examples
Example 1:
Input: n = 1
Output: "1"
Explanation:
The first term is defined directly as "1", with no computation needed.
Example 2:
Input: n = 4
Output: "1211"
Explanation:
- Term 1:
"1" - Term 2: read term 1 — one
1— giving"11" - Term 3: read term 2 — two
1s — giving"21" - Term 4: read term 3 — one
2, then one1— giving"1211"
Example 3:
Input: n = 6
Output: "312211"
Explanation:
- Term 4:
"1211" - Term 5: read term 4 — one
1, one2, two1s — giving"111221" - Term 6: read term 5 — three
1s, two2s, one1— giving"312211"
Constraints
1 <= n <= 30- The result is guaranteed to consist only of digits
1through9(no digit ever repeats nine or more times in a row across these terms, so no0appears).
Solution
Loading editor…
Sign in to get AI feedback on your answer. Your work is saved while you do.
Sign in to evaluate