Magical String: Question in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

A magical string str consists of only '1' and '2' and obeys the following rules −

The string str is magical because concatenating the number of contiguous occurrences of characters '1' and '2' generates the string str itself.

The first few elements of string str is the following −

str = "1221121221221121122……"

If we group the consecutive '1's and '2's in str, it will be −

1 22 11 2 1 22 1 22 11 2 11 22 ......

and the occurrences of '1's or '2's in each group are −

1 2 2 1 1 2 1 2 2 1 2 2 ......

We can see that the occurrence sequence above is the string itself.

We are given an integer num as input, and we are required to return the number of '1's in the first num number in the magical string str.

For example, if the input to the function is −

const num = 6;

Then the output should be −

const output = 3;

Output Explanation:

The first 6 elements of magical string S is "12211" and it contains three 1's, so return 3.

Example

The code for this will be −

 Live Demo

const num = 6;
const magicalString = (num = 1) => {
   let ind = 12;
   let str = '1221121221221121122';
   while(str.length < num){
      const end = str.substring(str.length - 1) === '2' ? '1' : '2';
      str = parseInt(str.substring(ind, ind + 1)) === 2 ? str + end + end : str + end;
      ind++;
   };
   return (str.substring(0, num).match(/1/g)||[]).length;
};
console.log(magicalString(num));

Output

And the output in the console will be −

3
raja
Updated on 04-Mar-2021 11:49:25

Advertisements