We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Count and Say

Difficulty: Medium


Problem Description

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

Given a positive integer n, return the nth element of the count-and-say sequence.


Key Insights

  • The sequence starts with "1" and builds upon itself through run-length encoding.
  • Each term in the sequence is derived from the previous term by counting consecutive digits.
  • The problem can be solved using either recursion or iteration.

Space and Time Complexity

Time Complexity: O(2^n) for recursive solution due to overlapping subproblems. O(n) for iterative solution as we generate each term based on the previous one. Space Complexity: O(n) due to the storage of the string for each term.


Solution

To solve the problem, we can use an iterative approach. The main idea is to construct the next term in the sequence by analyzing the current term. We will iterate through the characters of the string, count consecutive identical characters, and build the next string based on these counts and the respective character.

We will use a simple loop to traverse the string and a temporary string to accumulate the result for the next term.


Code Solutions

def countAndSay(n: int) -> str:
    if n == 1:
        return "1"
    
    current = "1"
    for _ in range(1, n):
        next_sequence = ""
        count = 1
        for j in range(1, len(current)):
            if current[j] == current[j - 1]:
                count += 1
            else:
                next_sequence += str(count) + current[j - 1]
                count = 1
        next_sequence += str(count) + current[-1]  # for the last group
        current = next_sequence
    return current
← Back to All Questions