Count and Say (LeetCode 38): Solution and Explanation

Medium
String

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

  1. Start with say = "1".
  2. Repeat n - 1 times: create an empty list or string builder parts and set i = 0.
  3. While i is inside the term, set j = i and advance j while say[j] == say[i].
  4. Append the count j - i followed by the digit say[i] to parts, then set i = j.
  5. After the scan, join parts into the new say.
  6. Return say.

Step-by-step example

n = 4
  1. Term 1 is "1". It is one run of a single 1, spoken as "11", so term 2 is "11".
  2. Term 2 is one run of two 1s, spoken as "21", so term 3 is "21".
  3. Term 3 has two runs. At i = 0, j stops at 1 because '1' differs from '2', giving "12". At i = 1, j reaches the end, giving "11".
  4. 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 say
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Precomputed table O(1)
Iterative run-length encoding O(L)
Recursion O(L)
Regular expression for runs O(L)
Time

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.

Space

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 j stops.
  • 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.