VOOZH about

URL: https://www.geeksforgeeks.org/dsa/look-and-say-sequence/

⇱ Look-and-Say Sequence - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Look-and-Say Sequence

Last Updated : 10 May, 2025

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.

  • 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

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

Using Recursive - O(2^n) Time and O(n + 2^n) Space

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:

  • Call the function recursively to get the (n-1)th term : prev = countAndSay(n - 1)
  • Initialize res = "" and count = 1.
  • Loop through the prev string from index 1:
  • If prev[i] == prev[i - 1], increment count. Else: append count and prev[i - 1] to result and reset count = 1
  • After the loop, append the count of last character followed by the last character. Note that in the loop, we process previous character, so the last character has to be processed separately.

Output
111221

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).

Iterative Solution - O(2^n) Time and O(2^n) Space

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.


Output
111221
Comment