The “Count and Say” sequence is a sequence of digit strings defined by the recursive formula:
countAndSay(1) = "1"
countAndSay(n)
is the previous term (i.e., countAndSay(n-1)
) read off. This means that you count the number of digits in groups of the same digit.For example, the first few terms of the sequence are:
countAndSay(1) = "1"
countAndSay(2) = "11"
(one 1)countAndSay(3) = "21"
(two 1s)countAndSay(4) = "1211"
(one 2 followed by one 1)countAndSay(5) = "111221"
(one 1, one 2, then two 1s)Given an integer n
, generate the n
-th term of the count-and-say sequence.
n
we need to handle?
n
to a reasonably small number (e.g., 1 <= n <= 30
).n
-th term of the count-and-say sequence.n <= 30
should suffice.Base Case: If n
is 1
, then we simply return "1"
.
countAndSay(1)
up to countAndSay(n)
.
"1"
.def countAndSay(n: int) -> str:
# Base term
result = "1"
for _ in range(n - 1):
result = next_term(result)
return result
def next_term(current_term: str) -> str:
next_term = []
i = 0
length = len(current_term)
while i < length:
count = 1
while i + 1 < length and current_term[i] == current_term[i + 1]:
count += 1
i += 1
next_term.append(f"{count}{current_term[i]}")
i += 1
return "".join(next_term)
# Example usage:
print(countAndSay(5)) # Expected output: "111221"
n
, and N is the number of terms to be generated (which is n
). Specifically, since the length of terms in the sequence can grow exponentially, precise complexity analysis is intricate, but an upper-bound estimate is O(2^N) for large N, due to the exponential growth of sequence lengths.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?