Find the n’th term in Look-and-say (Or Count and Say) Sequence. The look-and-say sequence is the sequence of below integers:
1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, …
How is above sequence generated?
n’th term in generated by reading (n-1)’th term.
The first term is "1" Second term is "11", generated by reading first term as "One 1" (There is one 1 in previous term) Third term is "21", generated by reading second term as "Two 1" Fourth term is "1211", generated by reading third term as "One 2 One 1" and so on
How to find n’th term?
Input: n = 3 Output: 21 Input: n = 5 Output: 111221
The idea is simple, we generate all terms from 1 to n. First two terms are initialized as “1” and “11”, and all other terms are generated using previous terms. To generate a term using previous term, we scan the previous term. While scanning a term, we simply keep track of count of all consecutive characters. For sequence of same characters, we append the count followed by character to generate the next term.
Below is implementation of above idea.
Thanks to Utkarsh for suggesting the above solution.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Convert an unbalanced bracket sequence to a balanced sequence
- Sum of the sequence 2, 22, 222, .........
- Gijswijt's Sequence
- Connell Sequence
- Alcuin's Sequence
- k-th number in the Odd-Even sequence
- De Bruijn sequence | Set 1
- Aronson's Sequence
- Beatty sequence
- Juggler Sequence
- Padovan Sequence
- Aliquot Sequence
- Sylvester's sequence
- Recaman's sequence
- Golomb sequence
- Sum of first N terms of Quadratic Sequence 3 + 7 + 13 + ...
- Mountain Sequence Pattern
- Program to find sum of the given sequence
- Generate a sequence with the given operations
- Euclid–Mullin Sequence
Improved By : chitranayal