Show problems as
Classic problem #38MediumString

Count and Say

Real-world version: Run Report Lines
Tracked in this browser only
Read Count and Say on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Learn the pattern firstString Manipulation · Strings, animated step by step

A test rig prints one report line per cycle, and every line is a string of digits.

The first line printed is 1. Each later line is a description of the line before it: read that earlier line from left to right, break it into runs of equal digits, and for every run write how many digits the run held followed by the digit itself. Glue the pieces together in run order and that is the new line.

So the line after 1 is 11, because the earlier line held one 1. The line after 11 is 21, because that line held two 1 digits.

Return the line printed in cycle n.

Examples

Example 1

Input
n = 3
Output
"21"

Cycle 1 prints `1`. Cycle 2 describes it as one `1`, giving `11`. Cycle 3 describes `11` as two `1` digits, giving `21`.

Example 2

Input
n = 6
Output
"312211"

Cycle 5 prints `111221`, which holds three `1` digits, then two `2` digits, then one `1`, so cycle 6 prints `312211`.

Example 3

Input
n = 8
Output
"1113213211"

Cycle 7 prints `13112221`. Reading its runs gives one `1`, one `3`, two `1` digits, three `2` digits, then one `1`, which glues to `1113213211`.

Constraints

  • 1 <= n <= 30

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def count_and_say(n: int) -> str:
Java
public String countAndSay(int n)