Count and Say

Medium

Topics
String

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

term 11
the answer
Term 1 of the sequence is 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.
The terms describe digits, not values: a run of eleven 1s is written as 11 followed by 1.
Input:  n = 1
Output: "1"
Explanation: The first term is given.

Example 2

term 11
term 211
term 321
term 41211
the answer
The term above it breaks into 1×2, 1×1, which is exactly what the answer spells out — including the final run, which is the one most often dropped.
Input:  n = 4
Output: "1211"
Explanation: The sequence runs 1, then 11, then 21, then 1211.

Example 3

term 11
term 211
term 321
term 41211
term 5111221
term 6312211
the answer
The term above it breaks into 3×1, 2×2, 1×1, which is exactly what the answer spells out — including the final run, which is the one most often dropped.
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

  1. Start with "1".
  2. Repeat n - 1 times: build the next term from the current one.
  3. To build it, walk the current term tracking the digit of the run you are in and how long it is.
  4. When the digit changes, append the run length and then the run digit, and start a new run.
  5. After the walk, append the final run — the step most often missed.
  6. 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 n times instead of n - 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 term
SensAI
Beta
Tap the mic to stop voice mode