![]() |
VOOZH | about |
Find the nth term in Look-and-say (Or Count and Say) Sequence. The look-and-say sequence is the sequence of the below integers: 1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, ...
How is the above sequence generated?
The nth term is generated by reading (n-1)th term.
Examples:
Input: n = 3
Output: 21
Explanation: The 3rd term of the sequence is 21
- 1st term: 1
- 2nd term: one 1 -> 11
- 3rd term: two 1s -> 21
Input: n = 4
Output: 1211
Explanation: The 4th term of the sequence is 1211
- 1st term: 1
- 2nd term: one 1 -> 11
- 3rd term: two 1s -> 21
- 4th term: one 2 one 1 -> 1211
Input: n = 1
Output: 1
Explanation: The first term of the sequence is 1
Idea is to recursively call for n-1 to generate the previous term. Then we build the nth or current term using the (n-1)th or previous term
How to build current term using previous? To generate a term using the previous term, we scan the previous term. While scanning a term, we simply keep track of the count of all consecutive characters. For a sequence of the same characters, we append the count followed by the character to generate the next term.
Step by Step Algorithm:
(n-1)th term : prev = countAndSay(n - 1) = "" and count = 1.prev string from index 1:prev[i] == prev[i - 1], increment count. Else: append count and prev[i - 1] to result and reset count = 1111221
Why is the time complexity exponential?
The next term can be at-most double the size of previous term. We get double size when all characters are different. So an upper bound on the time complexity would be O(2n). We need this long string also for output and O(n) space for recursion. That is why the space is O(2n + n).
Instead of recursively generating the previous term, we build all terms one by one from first term which is "1" to the nth term. To generate the next term, we use the same idea as used in the above recursive solution.
111221