Skip to main content
LeetCode 38, Medium. Topics: String. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 14 parametrized pytest cases, and a playground notebook:

Problem

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 each maximal group of consecutive identical characters with the concatenation of the length of the group followed by the character itself. 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.

Examples

Constraints

  • 1 <= n <= 30
Follow up: Could you solve it iteratively?

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

Last modified on September 7, 2026