Open In App

JavaScript Program to Generate Number Sequence

Last Updated : 18 Jul, 2024
Comments
Improve
Suggest changes
2 Likes
Like
Report

Find the n’th term in the 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? 
n’th 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

How to find n’th term? 

Example: 

Input: n = 3
Output: 21
Input: n = 5
Output: 111221

Number sequence using Iterative Approach

In this approach, we iteratively generate each term of the sequence starting from the base case "1". After which we maintain a current term and use it to generate the next term by counting consecutive digits. The process continues until we reach the nth term.

Example: The below code implements a JavaScript Program to generate a number sequence using an iterative approach.


Output
The 5th term of the Count and Say sequence is: 111221

Time Complexity: O(2^N)

Auxiliary Space: O(2^N)

Using Recursive Approach

In the recursive approach, we define a function to generate the nth term of the sequence based on the (n-1)th term. After which we recursively call this function to generate each term until we reach the base case. The base case is when n is 1, in which case we return "1" as the first term of the sequence.

Example: The below code implements a Program to generate a number sequence using a recursive approach.


Output
The 5th term of the Count and Say sequence (recursive approach) is: 111221

Time Complexity: O(N*2^N)

Auxiliary Space: O(n)

Using Dynamic Programming Approach

In the dynamic programming approach, we use an array to store the previously computed terms of the sequence. This way, we avoid recalculating the terms multiple times, which helps to optimize the process and reduce time complexity. We generate each term based on the previous term stored in the array and continue this process until we reach the nth term.

Example: The below code implements a JavaScript program to generate a number sequence using a dynamic programming approach.


Output
21
111221
1113213211

Time Complexity: O(N*2^N)

Auxiliary Space: O(N*2^N)


Next Article

Similar Reads