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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Convert an unbalanced bracket sequence to a balanced sequence
- Find a valid parenthesis sequence of length K from a given valid parenthesis sequence
- Given a sequence of words, print all anagrams together | Set 2
- Count Possible Decodings of a given Digit Sequence
- Check if a given sequence of moves for a robot is circular or not
- Form minimum number from given sequence
- String with additive sequence
- Longest consecutive sequence in Binary tree
- Juggler Sequence
- Padovan Sequence
- Aliquot Sequence
- Find bitonic point in given bitonic sequence
- Recaman's sequence
- Second most repeated word in a sequence
- Lexicographically smallest rotated sequence | Set 2
- Thue-Morse sequence
- Sum of the sequence 2, 22, 222, .........
- Sylvester's sequence
- Golomb sequence
- Digit - Product - Sequence
Improved By : chitranayal