Strings String basics

132. Count and Say

Medium

The count-and-say sequence is a list of digit strings. The first term is "1". Every later term describes the term before it, read aloud from left to right.

To describe a term, split it into groups of equal digits that sit next to each other. For each group, write how many digits it has, then the digit itself. For example, "3322251" has the groups 33, 222, 5 and 1. Read aloud, that is "two 3s, three 2s, one 5, one 1", so its description is "23321511".

The sequence starts "1", "11", "21", "1211", "111221". Given n, return the n-th term.

Answers are shown in double quotes.

Example 1

Input: n = 5

Output: "111221"

Explanation: Term 4 is "1211": one 1, one 2, two 1s. Writing each count before its digit gives "11", "12" and "21", so term 5 is "111221".

Example 2

Input: n = 1

Output: "1"

Explanation: The first term is "1". It describes nothing.

Example 3

Input: n = 8

Output: "1113213211"

Explanation: Term 7 is "13112221": one 1, one 3, two 1s, three 2s, one 1. That reads as "1113213211".

Check your understanding

Work out the answer for this input before you write any code.

n = 6

Constraints

  • 1 ≤ n ≤ 50

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.