MediumStrings

Count and Say

LeetCode
1 approach, code in all languages

The count-and-say sequence is built by describing the previous term out loud. The first term is the string "1". To create any later term, scan the previous term left to right, group consecutive identical digits together, and write down how many there are followed by the digit itself.

For example, "1" is spoken as "one 1" which becomes "11", and "11" is spoken as "two 1s" which becomes "21". Given a position n, return the n-th term of this sequence.

Example 1

Input: n = 1

Output: "1"

By definition the sequence starts with the string 1.

Example 2

Input: n = 4

Output: "1211"

The chain is 1 -> "11" -> "21" -> "1211", so the fourth term is 1211.

Constraints

  • 1 <= n <= 30
  • Each term is generated only from the term directly before it
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now