LeetCode #38 Medium

Count and Say

Term 1 is "1"; each next term reads the previous aloud ("1211" → one 1, one 2, two 1s → "111221"). Return term n.

stringsimulation
Open on LeetCode ↗
02

Intuition

💡

Pure run-length encoding applied n−1 times: scan the current string, group equal consecutive digits, and emit count+digit for each run. There's no closed form — simulate.

03

Approach

1

Describe one string

Walk with a run pointer: count how many times the current char repeats, append str(count) + char, jump past the run.

2

Iterate n−1 times

Start from "1" and re-describe. Strings roughly grow ~30% per step (Conway's constant λ ≈ 1.304).

3

Groupby shortcut

itertools.groupby does the run detection declaratively — same complexity.

04

Solution & live demo

python
1from itertools import groupby
2 
3class Solution:
4 def countAndSay(self, n):
5 s = "1"
6 for _ in range(n - 1):
7 s = "".join(str(len(list(g))) + d for d, g in groupby(s))
8 return s
05

Edge cases

n = 1

Loop runs zero times → "1".

Runs longer than 9

Can't happen — no three equal consecutive digits ever appear in the sequence, and counts stay single-digit.

06

Complexity

Time
O(λⁿ)
Space
O(λⁿ)
String length grows geometrically.