Count and Say (LeetCode 38): Solution and Explanation
Each term of the count-and-say sequence is the previous term read aloud: split it into runs of equal digits and write each run as its count followed by its digit. Starting from "1", apply that run-length encoding n - 1 times.
Intuition
Reading "21" aloud gives "one 2, one 1", which is written "1211". That is exactly a run-length encoding where the count comes before the digit.
So there is no formula to discover. The work is a loop that encodes the current term, and an outer loop that repeats it n - 1 times.
Runs are found with two pointers: i marks where a run starts and j walks right while the digit matches say[i]. The run length is j - i, and the next run starts at j.
Approach: Iterative run-length encoding
- Start with
say = "1". - Repeat n - 1 times: create an empty list or string builder
partsand seti = 0. - While
iis inside the term, setj = iand advancejwhilesay[j] == say[i]. - Append the count
j - ifollowed by the digitsay[i]toparts, then seti = j. - After the scan, join
partsinto the newsay. - Return
say.
Step-by-step example
n = 4
- Term 1 is
"1". It is one run of a single 1, spoken as"11", so term 2 is"11". - Term 2 is one run of two 1s, spoken as
"21", so term 3 is"21". - Term 3 has two runs. At
i = 0,jstops at 1 because'1'differs from'2', giving"12". Ati = 1,jreaches the end, giving"11". - Joining the pieces gives term 4 =
"1211", which is the answer.
Code: Python, Java, C++
1class Solution:
2 def countAndSay(self, n: int) -> str:
3 say = "1"
4 for _ in range(n - 1):
5 parts = []
6 i = 0
7 while i < len(say):
8 j = i
9 while j < len(say) and say[j] == say[i]:
10 j += 1
11 parts.append(str(j - i) + say[i])
12 i = j
13 say = "".join(parts)
14 return say1class Solution {
2 public String countAndSay(int n) {
3 String say = "1";
4 for (int t = 1; t < n; t++) {
5 StringBuilder parts = new StringBuilder();
6 int i = 0;
7 while (i < say.length()) {
8 int j = i;
9 while (j < say.length() && say.charAt(j) == say.charAt(i)) {
10 j++;
11 }
12 parts.append(j - i).append(say.charAt(i));
13 i = j;
14 }
15 say = parts.toString();
16 }
17 return say;
18 }
19}1class Solution {
2public:
3 string countAndSay(int n) {
4 string say = "1";
5 for (int t = 1; t < n; t++) {
6 string parts;
7 int i = 0;
8 while (i < (int)say.size()) {
9 int j = i;
10 while (j < (int)say.size() && say[j] == say[i]) {
11 j++;
12 }
13 parts += to_string(j - i) + say[i];
14 i = j;
15 }
16 say = parts;
17 }
18 return say;
19 }
20};Time and space complexity
O(L)
Each pass scans the current term once, so the total work is the sum of the lengths of terms 1 through n. Terms grow by roughly 1.3 times per step (Conway's constant), so that sum is dominated by the last few terms and is proportional to L, the length of the answer.
O(L)
Only the current term and the pieces of the next one are kept, and both are at most about L characters.
Other approaches
Recursion (time O(L), space O(L + n))
Compute countAndSay(n - 1) recursively and encode it. It is the same algorithm, but uses n stack frames for no benefit.
Regular expression for runs (time O(L), space O(L))
Match runs with a backreference pattern such as (.)\1* and replace each match with its length plus its first character. It is short to write, but hides the scan and is usually slower than a manual loop.
Precomputed table (time O(1), space O(total length of 30 terms))
Because n is at most 30, all answers could be generated once and stored. That works for the judge but shows nothing about the algorithm.
Common mistakes
- Writing the digit before the count. The spoken form is count first: three 1s is
"31", not"13". - Forgetting the last run. If the scan only emits a run when the digit changes, the final run is lost at the end of the string. The two-pointer loop avoids this because every run is emitted when
jstops. - Building the next term with repeated string concatenation in languages with immutable strings. Use a list and join, or a StringBuilder, to keep each pass linear.
- Running the outer loop n times instead of n - 1. Term 1 is already
"1".
Frequently asked questions
Can a count ever be larger than 3?
No. Starting from "1", no term ever contains four equal digits in a row, so every count is 1, 2 or 3 and every term only uses the digits 1, 2 and 3. The code does not rely on this, but it explains why the terms look the way they do.
How fast do the terms grow?
The length grows by a factor that approaches Conway's constant, about 1.3036, per term. Term 30 has 4,462 digits, which is small enough that the straightforward loop is fast.
Why use two pointers instead of a counter?
A counter that resets when the digit changes works too, but it needs a separate step after the loop to emit the final run. With i and j, each run is complete as soon as j stops, so every run is handled the same way.
Is there a closed-form formula for the nth term?
No. The sequence has deep structure (Conway showed it splits into 92 recurring elements), but there is no shortcut to the nth term that avoids building the earlier ones.