Count and Say
The count-and-say sequence is defined recursively: the first term is "1", and every later term is produced by reading the previous term aloud in digits — scanning it left to right and, for each run of identical adjacent digits, emitting the run's length followed by the digit itself. For example "1" reads as "one 1" → "11", which reads as "two 1s" → "21", which reads as "one 2, one 1" → "1211". Given an integer n, return the n-th term of the sequence as a string.
- 1 <= n <= 30
- Every term is a string of digits
n = 1"1"n = 4"1211"n = 5"111221"Generating the "Count and Say" sequence is like reading a string out loud. If you see the string "11", you say "two ones", which becomes "21". Each term is a literal description of the digits found in the previous term.
To generate the next term, we must translate a string like "1211" into its spoken description. The most reliable way is to walk through the string and count how many times the same character appears in a row (a "streak").
As soon as the character changes, we record the count and the digit we were just looking at, then reset our counter for the new digit.
We start with the base case "1" and repeat the "reading" process n-1 times. Using an iterative approach avoids recursion overhead and keeps the memory usage focused on the growing string.
res = "1"
for _ in range(n - 1):
next_val = []
i = 0
while i < len(res):
count = 1
# Calculate the length of the current digit streak
while i + 1 < len(res) and res[i] == res[i+1]:
count += 1
i += 1
# Append "count" followed by the "digit"
next_val.append(str(count) + res[i])
i += 1
res = "".join(next_val)
return rescount & say
Generating the 5th term from the 4th term: "1211".