MediumNo. 0038

Count and Say — LeetCode 38 Python Solution

Pattern
Hash Map
Topics
String
Reading time
3 min

The 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 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).

Example

Example
countAndSay(1) = "1"
countAndSay(2) = RLE of "1" = "11"
countAndSay(3) = RLE of "11" = "21"
countAndSay(4) = RLE of "21" = "1211"

Python solution

PythonSolution
class Solution:
    def countAndSay(self, n: int) -> str:
        s = '1'
        for _ in range(n - 1):
            i = 0
            t = []
            while i < len(s):
                j = i
                while j < len(s) and s[j] == s[i]:
                    j += 1
                t.append(str(j - i))
                t.append(str(s[i]))
                i = j
            s = ''.join(t)
        return s

Complexity

Time
O(n × m)where n is the input parameter representing the term to generate, and m is the maximum length of the string in the sequence
Space · auxiliary
O(1) to O(n)

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 38. Count and Say is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0006Zigzag ConversionMedium
0008String to Integer (atoi)Medium
0058Length of Last WordEasy
0065Valid NumberHard
0068Text JustificationHard
0214Shortest PalindromeHard

Frequently asked questions

How hard is LeetCode 38. Count and Say?

LeetCode 38. Count and Say is rated Medium on LeetCode.

What topics does LeetCode 38. Count and Say cover?

LeetCode 38. Count and Say is tagged String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.