1. Recursive Generation with RLE Helper
Intuition
1. Base case: If n == 1, return "1".
2. Recursively get prev = countAndSay(n - 1).
3. Traverse prev counting consecutive identical characters, constructing the RLE string.
4. Return the newly constructed string.
When to apply: Natural mathematical implementation directly following the problem definition.
Algorithm
- If n == 1 return "1".
- Recurse to get previous string.
- Scan previous string for runs of identical characters.
- Append run length + character to result.
- Return encoded string.
Recursive Generation with RLE Helper
2 of 2 questions left todayObservation: Base case $n = 1$ is predefined as '1'
Observation: Base case n = 1 is predefined as '1'.
Decision: Return '1' directly without running run-length encoding.
Invariant: The recursion terminates at n = 1 establishing the ground truth term.
#include <iostream>#include <string> class Solution {public: std::string countAndSay(int n) { if (n == 1) return "1"; std::string prev = countAndSay(n - 1); std::string result = ""; int len = prev.size(); for (int i = 0; i < len;) { int j = i; while (j < len && prev[j] == prev[i]) { j++; } result += std::to_string(j - i) + prev[i]; i = j; } return result; }}; int main() { Solution sol; std::cout << sol.countAndSay(1) << std::endl; // "1" std::cout << sol.countAndSay(4) << std::endl; // "1211" return 0;}Time & Space Complexity
- Time complexity:
O(2^n)— Each iteration grows the string length by approximately a factor of 1.3 to 1.5 (asymptotically bounded by O(2n)). - Space complexity:
O(n) call stack + O(2^n) output
Why Brute Force Doesn't Scale:
Naive brute force re-examines already processed substrings multiple times.
For N = 105, O(N2) requires 1010 operations (TLE), while O(N) finishes in < 10ms.