The count-and-say sequence is a sequence of digit strings defined by the recursive formula:
countAndSay(1) = "1"countAndSay(n) is the run-length encoding of countAndSay(n - 1).Run-length encoding (RLE) is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string "3322251" we replace "33" with "23", replace "222" with "32", replace "5" with "15" and replace "1" with "11". Thus the compressed string becomes "23321511".
Given a positive integer n, return the nth element of the count-and-say sequence.
Example 1:
Input: n = 4
Output: "1211"
Explanation:
countAndSay(1) = "1" countAndSay(2) = RLE of "1" = "11" countAndSay(3) = RLE of "11" = "21" countAndSay(4) = RLE of "21" = "1211"
Example 2:
Input: n = 1
Output: "1"
Explanation:
This is the base case.
Constraints:
1 <= n <= 30When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The count-and-say sequence is built step by step, where each new term is created by reading out loud the digits of the previous term. To solve this by brute force, you simply start with the very first term and physically generate every single intermediate term one after another until you reach the target step you care about.
Here's how the algorithm would work step-by-step:
The count-and-say sequence is built by reading the previous number aloud, grouping identical digits together, and counting how many times each digit appears. To find a specific term in the sequence, you simply start at the very beginning and repeatedly build each next number from the one you just made.
Here's how the algorithm would work step-by-step:
| Case | How to Handle |
|---|---|
| Minimum input where n equals 1 | The base case returns the starting string 1 immediately without entering the loop. |
| Inputs with large n values leading to long strings | Iterative generation avoids recursion depth limits while string builder buffers efficiently manage memory allocation. |
| Consecutive identical digits across the entire string | The counting pointer correctly accumulates the total length before appending the count and single digit. |
| All distinct digits where every run length is one | The inner loop correctly formats each digit with a prefix count of one. |
| Invalid non-positive integers for n | The problem guarantees a positive integer constraint so zero or negative inputs are not applicable. |