The count-and-say sequence is a list of digit strings. The first term is "1". Every later term describes the term before it out loud: split it into runs of the same digit and, for each run from left to right, write how many digits it has followed by the digit itself.
So "1" is read as "one 1", giving "11". That is read as "two 1s", giving "21". Given a whole number n, return the n-th term as a string.
Example 1
Input: n = 5 Output: "111221" Why: term 4 is "1211": one 1, one 2, two 1s
2 more examples and the constraints
Example 2
Input: n = 1 Output: "1" Why: the first term is fixed
Example 3
Input: n = 6 Output: "312211" Why: "111221" is three 1s, two 2s, one 1
Constraints
- 1 ≤ n ≤ 30
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Recursion on n − 1O(L)
- Build the terms in a loopO(L)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for n = 30 | Verdict |
|---|---|---|---|
| Recursion on n − 1 | O(L) | Passes; uses the call stack | |
| Build the terms in a loop | O(L) | Best; no recursion |
L = length of the n-th term, 4,462 characters for n = 30.
Edge cases to test
- n = 1. Return "1" without reading anything.
- The last run. The run that reaches the end of the term has no digit after it to trigger it, so it must be said after the loop or on the end check.
- Runs longer than one. "111221" holds three 1s: count the whole run, not one digit at a time.
- n = 30. The answer has 4,462 characters, so build it with a list or builder.
Common mistakes
- Forgetting to say the final run, so every term loses its last piece.
- Writing the digit before the count, so one 2 comes out as "21" instead of "12".
- Looping n times instead of n − 1, which returns the next term.
How to talk through it
- 1Clarify. Is term 1 always "1"? Is the answer a string? How big can n get?
- 2Say the rule on a small case. Read "1211" out loud: one 1, one 2, two 1s, giving "111221".
- 3Write the reader. One pass with a run counter; say a run when the digit changes or the term ends.
- 4Loop it. Start from "1" and apply the reader n − 1 times; mention that the recursive version works too.
- 5Test out loud. Check n = 1, n = 4 and n = 5 against terms worked by hand.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?