




Sponsored
This approach involves constructing the sequence iteratively. We start from the base case, which is '1', and iteratively build up the strings by counting and saying the digits from the last constructed string.
Time Complexity: O(2^n) as the length of the string grows exponentially.
Space Complexity: O(2^n) for storing the string.
1def countAndSay(n: int) -> str:
2    result = '1'
3    for _ in range(n - 1):
4        current_result = ''
5        i = 0
6        while i < len(result):
7            count = 1
8            while i + 1 < len(result) and result[i] == result[i + 1]:
9                i += 1
10                count += 1
11            current_result += str(count) + result[i]
12            i += 1
13        result = current_result
14    return result
15
16if __name__ == "__main__":
17    print(countAndSay(4))Python's solution leverages concise string concatenation along with iteration to accumulate the count and the said digits for producing the next line in the sequence.
The recursive approach defines the function countAndSay recursively by computing countAndSay(n-1), then generating the count-and-say encoding for it.
This method involves less memory usage on the function stack compared to an iterative approach but still leverages recursion for elegance.
Time Complexity: O(2^n) as strings grow exponentially.
Space Complexity: O(2^n) due to storing strings and O(n) recursion stack.
1using System.Text;
public class Solution {
    private string NextSequence(string seq) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < seq.Length;) {
            char currentChar = seq[i];
            int count = 0;
            while (i < seq.Length && seq[i] == currentChar) {
                i++;
                count++;
            }
            result.Append(count).Append(currentChar);
        }
        return result.ToString();
    }
    public string CountAndSay(int n) {
        if (n == 1) return "1";
        string prevResult = CountAndSay(n - 1);
        return NextSequence(prevResult);
    }
    public static void Main() {
        Solution sol = new Solution();
        Console.WriteLine(sol.CountAndSay(4));
    }
}C# implementation makes use of recursion to compute sequences with NextSequence extending every string based on counting each digit from previous results.