LeetCode #38 Medium

Count and Say

Count and Say is LeetCode 38 (Medium). The sequence starts with "1", and every later term is made by reading the previous term aloud: for each block of the same digit in a row, say how many there are, then the digit. Given n, return the nth term as a string.

n is at most 30, and term 30 has 4,462 characters, so building every term in turn is fast enough.

Constraints
  • 1 <= n <= 30
stringsimulation
Open on LeetCode ↗
02

Intuition

There is no shortcut to term n: each term is defined only by the one before it, so the solution builds terms 2, 3, …, n in order.

One step is run-length encoding. Split the term into runs, blocks of the same digit standing next to each other, and write each run as its length followed by its digit.

Only neighbouring equal digits form a run. In "1211" the 1 at the front and the 1s at the end are separate runs, so it reads as one 1, one 2, two 1s: "111221".

How to spot this pattern

Each term is defined only from the previous one, so simulate it. The inner loop is run-length encoding: find where a run of equal characters ends, write its length, jump past it. String Compression (443) uses the same scan.

03

Approach

Try it first

Before reading on: write out terms 1 to 5 by hand. While reading a term, how do you know a run has ended, and what do you write down at that moment?

1

Start from term 1

Set s = "1" and repeat the describe step n - 1 times: term 1 is given, so only the terms after it are computed. For n = 1 the loop does not run and "1" is returned.

2

Find where each run ends

Keep i on the first digit of the current run and move j forward while s[j] == s[i]. When j reaches a different digit or the end of the string, the run is s[i:j], and its length is j - i.

3

Write the count, then the digit

Append str(j - i) + s[i] to a list of pieces, then set i = j so the next run starts right after this one. Every digit is read once per term. Joining the pieces once at the end avoids rebuilding a growing string for every run.

4

Move to the next term

When i reaches the end of s, "".join(parts) is the next term. Assign it to s and start the next round; after the last round, return s.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def countAndSay(self, n: int) -> str:
▶3 s = "1"
▶4 for _ in range(n - 1):
▶5 parts = []
▶6 i = 0
▶7 while i < len(s):
▶8 j = i
▶9 while j < len(s) and s[j] == s[i]:
▶10 j += 1
▶11 parts.append(str(j - i) + s[i])
▶12 i = j
▶13 s = "".join(parts)
▶14 return s
term 11term 2 so faremptys = "1" → 3 rounds to reach term 4
n4
s"1"term 1
Term 1 is the seed "1". Each round reads the current term aloud to make the next, so 3 rounds reach term 4.
term 11ij: endterm 2 so faremptys[0] = 1 → run of 1 is 1 long so far
i0
j1
run1copies of 1
A new run starts at i = 0 with digit 1. It matches itself, so j steps past it: the run has 1 digit so far.
term 11ij: endterm 2 so far11one 1end of term → write "11"
run1 × 1
write"11"
i0 → 1
j reached the end of the term, so the run is over: one 1. Write the count first, then the digit: "11". Then i jumps to 1.
term 211term 3 so faremptyterm 2 = "11" → read it next
s"11"term 2
length2
That one pair is term 2 = "11". It replaces s, and the next round reads it from the start.
term 211ijterm 3 so faremptys[0] = 1 → run of 1 is 1 long so far
i0
j1
run1copies of 1
A new run starts at i = 0 with digit 1. It matches itself, so j steps past it: the run has 1 digit so far.
term 211ij: endterm 3 so faremptys[1] = 1 → run of 1 is 2 long so far
i0
j2
run2copies of 1
s[1] is also 1, the same digit standing next to the run, so the run grows to 2.
term 211ij: endterm 3 so far21two 1send of term → write "21"
run2 × 1
write"21"
i0 → 2
j reached the end of the term, so the run is over: two 1s. Write the count first, then the digit: "21". Then i jumps to 2.
term 321term 4 so faremptyterm 3 = "21" → read it next
s"21"term 3
length2
That one pair is term 3 = "21". It replaces s, and the next round reads it from the start.
term 321ijterm 4 so faremptys[0] = 2 → run of 2 is 1 long so far
i0
j1
run1copies of 2
A new run starts at i = 0 with digit 2. It matches itself, so j steps past it: the run has 1 digit so far.
term 321ijterm 4 so far12one 2s[1] = 1 ≠ 2 → write "12"
run1 × 2
write"12"
i0 → 1
s[1] is 1, a different digit, so the run is over: one 2. Write the count first, then the digit: "12". Then i jumps to 1, the first digit of the next run, so no digit is read twice.
term 321ij: endterm 4 so far12one 2s[1] = 1 → run of 1 is 1 long so far
i1
j2
run1copies of 1
A new run starts at i = 1 with digit 1. It matches itself, so j steps past it: the run has 1 digit so far.
term 321ij: endterm 4 so far12one 211one 1end of term → write "11"
run1 × 1
write"11"
i1 → 2
j reached the end of the term, so the run is over: one 1. Write the count first, then the digit: "11". Then i jumps to 2.
term 41211term 4 = "1211"
s"1211"term 4
length4
The 2 pairs joined together give term 4 = "1211". It replaces s. That was round 3, the last one.
term 41211return "1211"
answer"1211"
Term 4 is "1211". Each round read its term once from left to right, so the total work is the combined length of the terms.
05

Common pitfalls

Looping n times instead of n − 1

✗ Wrong
s = "1"
for _ in range(n):
✓ Right
s = "1"
for _ in range(n - 1):

"1" already is term 1, so only n - 1 describe steps are needed. Looping n times returns term n + 1: "11" for n = 1.

Writing the digit before the count

✗ Wrong
parts.append(s[i] + str(j - i))
✓ Right
parts.append(str(j - i) + s[i])

The rule is "how many, then which digit". Swapping the order turns "21" into "2111" instead of "1211", and every later term goes wrong.

Moving i by one instead of to the end of the run

✗ Wrong
parts.append(str(j - i) + s[i])
i += 1
✓ Right
parts.append(str(j - i) + s[i])
i = j

With i += 1 the scan starts again inside the run it just described, so "11" is read as two 1s and then one 1: "2111" instead of "21".

06

Complexity

Time
O(L)
Space
O(L)
L is the length of term n (4,462 characters for n = 30). Each round reads one term once. Terms grow by about 1.3× per step, so all the earlier terms together add up to only a few times L. Space holds the current term and the one being built.
07

Count and Say FAQ

Is count and say the same as the look and say sequence?

Yes. Mathematicians call it the look-and-say sequence, studied by John Conway. He showed that each term is about 1.3036 times as long as the one before (Conway's constant), and that starting from "1" no digit other than 1, 2 and 3 ever appears. So a count is always a single digit.

Can it be solved recursively?

Yes: countAndSay(n) describes the string returned by countAndSay(n - 1), and countAndSay(1) returns "1". It does the same work but keeps n calls on the stack. LeetCode's follow-up asks for the iterative version shown here.

Is there a shorter way to write it in Python?

itertools.groupby splits a string into runs of equal characters, so one round becomes s = "".join(str(len(list(g))) + d for d, g in groupby(s)). It runs in the same time; the two-pointer loop just shows the run detection explicitly.