Similar Problems

Similar Problems not available

Count And Say - Leetcode Solution

LeetCode:  Count And Say Leetcode Solution

Difficulty: Medium

Topics: string  

Problem Statement: The count-and-say sequence is a sequence of digit strings defined by the recursive formula:

  • countAndSay(1) = "1"
  • countAndSay(n) is the way you would "say" the digit string from countAndSay(n-1), which is then converted into a different digit string.

To determine how you "say" a digit string, split it into the minimal number of groups so that each group is a contiguous section all of the same character. Then for each group, say the number of characters, followed by the character. To convert the saying into a digit string, replace the counts with a number and concatenate every saying.


Input: n = 4 Output: "1211" Explanation: countAndSay(1) = "1" countAndSay(2) = say "1" = one 1 = "11" countAndSay(3) = say "11" = two 1's = "21" countAndSay(4) = say "21" = one 2 + one 1 = "12" + "11" = "1211"

Approach: We can solve this problem by applying a recursive approach. We can start from n=1 and keep returning the resulting string by applying the rule of the count-and-say sequence. For a given n, we can recursively call the function to calculate the string countAndSay(n-1) which is given. To get the required string countAndSay(n), we can apply the following steps:

  1. Initialize the resulting string as an empty string.
  2. Initialize count as 1 and the starting character as the first character in countAndSay(n-1).
  3. Traverse the string countAndSay(n-1) from the second character to the end.
  4. If the current character is the same as the previous character, increment the count.
  5. If the current character is different from the previous character, append the count and the previous character to the resulting string and start a new count for the current character.
  6. After the traversal is complete, append the last count and character to the resulting string and return the resulting string.

For example, consider the following code for the countAndSay function:

def countAndSay(n: int) -> str:
    if n == 1:
        return "1"
    res = ""
    prev = countAndSay(n-1)
    count = 1
    prev_char = prev[0]
    for i in range(1, len(prev)):
        if prev[i] == prev_char:
            count += 1
            res += str(count) + prev_char
            count = 1
            prev_char = prev[i]
    res += str(count) + prev_char
    return res

Time Complexity: Each recursive call performs a linear traversal of the previous string, so the time complexity of the countAndSay function is O(n*m), where n is the input value of n, and m is the length of the previous string. In the worst case, m = 2^(n-1) which is the length of the maximum possible string.

Space Complexity: Each recursive call requires a new string of length at most 2^(n-1). Therefore, the space complexity of the countAndSay function is O(2^n).

Count And Say Solution Code