Tensorum
LeetCode 38 · Parsing / Conversion

Count and Say

LeetCode 38 · Medium · solution, intuition & step-by-step walkthrough

Term n = run-length encoding of term n−1.

MediumString
49 msruntime · beats 6%
51.3 MBmemory · beats 100%
1approach
4accepted runs · last 23 Apr 2024

This is how I solved Count and Say (LeetCode 38), a medium problem from the Parsing / Conversion pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Each term describes the previous one: read it as runs of equal digits and write 'count then digit' for each run. Recursively get term n−1 and run-length encode it.

Approach

  1. 1

    Base: n = 1 → '1'.

  2. 2

    Get say = term(n−1).

  3. 3

    Scan runs: count equal neighbours, append count + digit.

How I solved it

Recursive run-length encodingPythonO(L) per term
class Solution:
    def countAndSay(self, n):
        if n == 1:
            return "1"
        say = self.countAndSay(n - 1)
        result = ""
        i = 0
        while i < len(say):
            char = say[i]
            count = 1
            while i < len(say) - 1 and say[i] == say[i + 1]:
                count += 1
                i += 1
            result += str(count) + char
            i += 1
        return result
Loading the step-through…

Count and Say — FAQ

What is the intuition behind Count and Say?

Each term describes the previous one: read it as runs of equal digits and write 'count then digit' for each run. Recursively get term n−1 and run-length encode it.

How do you solve Count and Say (LeetCode 38)?

1. Base: n = 1 → '1'. 2. Get say = term(n−1). 3. Scan runs: count equal neighbours, append count + digit.

What is the time and space complexity of Count and Say?

Time: O(total length). Space: O(total length). (Accepted approach: Recursive run-length encoding.)

What are common mistakes in Count and Say?

Build the result with a list in Python; repeated string concatenation is slower.