Generate the n-th term of the count-and-say sequence.
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 run-length encoding of `countAndSay(n - 1)`.
Examples
Input: n = 1
Output: "1"
Explanation: Combining the input according to Count and say logic yields "1".
Input: n = 4
Output: "1211"
Explanation: Combining the input according to Count and say logic yields "1211".
Complexity
Time Complexity: O(2^N)
Space Complexity: O(2^N)
Hints
š” Hint 1:
Base case: countAndSay(1) = "1".
š” Hint 2:
For each step from 2 to n, apply run-length encoding on the previous string.
š” Hint 3:
Count contiguous identical digits and append count + digit to form the next string.
Editorial & Approach
Problem Overview & Intuition
Iteratively construct the sequence starting from "1". For each transition, run-length encode consecutive identical digits into [count, digit], producing the next term in the sequence.
Step-by-Step Approach
- Initialize
curr = "1". - Iterate
ifrom2ton. - Traverse
currusing two pointers or a loop counting contiguous duplicate characters. - Append
count + chartonext. - Update
curr = next. - Return
curr.
Optimal Implementation (JavaScript)
function countAndSay(n) {
let curr = '1';
for (let i = 2; i <= n; i++) {
let next = '', j = 0;
while (j < curr.length) {
let count = 1;
while (j + 1 < curr.length && curr[j] === curr[j + 1]) {
count++;
j++;
}
next += count + curr[j];
j++;
}
curr = next;
}
return curr;
}
Complexity Analysis
Time Complexity
O(2^N) ā sequence length approximately grows by factor of 1.3 per step.
Space Complexity
O(2^N) ā storage for the string.
Edge Cases & Corner Traps Handled
- n = 1: returns "1".
- n = 2: returns "11".
- n = 4: returns "1211".