Magical String: Question in JavaScript

A magical string consists of only '1' and '2' characters and has a unique property: the sequence of consecutive character group lengths generates the string itself.

Understanding the Magical String

The magical string starts as "1221121221221121122..." where grouping consecutive characters reveals the pattern:

Original: 1 22 11 2 1 22 1 22 11 2 11 22 ......
Lengths:  1 2  2  1 1 2  1 2  2  1 2  2  ......

Notice how the length sequence (1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2...) matches the original string itself.

Problem Statement

Given an integer num, return the count of '1's in the first num characters of the magical string.

Example

For num = 6, the first 6 characters are "122112", which contains three '1's.

const magicalString = (num = 1) => {
    if (num <= 0) return 0;
    
    let str = '122';
    let index = 2;  // Start from the 3rd element to generate more
    
    while (str.length < num) {
        const count = parseInt(str[index]);
        const nextChar = str[str.length - 1] === '1' ? '2' : '1';
        
        // Add 'count' number of nextChar
        str += nextChar.repeat(count);
        index++;
    }
    
    // Count '1's in first num characters
    return str.substring(0, num).split('').filter(char => char === '1').length;
};

const num = 6;
console.log(`Input: ${num}`);
console.log(`First ${num} characters: ${magicalString.toString().substring(0, num)}`);
console.log(`Count of 1's: ${magicalString(num)}`);
Input: 6
First 6 characters: 122112
Count of 1's: 3

How the Algorithm Works

The solution builds the magical string iteratively:

  1. Start with initial string "122"
  2. Use each character as a count to determine how many of the next alternating character to add
  3. Continue until we have at least num characters
  4. Count the '1's in the first num positions

Optimized Solution

const magicalStringOptimized = (num) => {
    if (num <= 0) return 0;
    if (num <= 3) return [0, 1, 1, 2][num];
    
    let ones = 1;  // Count of 1's so far
    let str = [1, 2, 2];  // Use array for better performance
    let index = 2;
    
    while (str.length < num) {
        const count = str[index];
        const nextChar = str[str.length - 1] === 1 ? 2 : 1;
        
        for (let i = 0; i < count && str.length < num; i++) {
            str.push(nextChar);
            if (nextChar === 1) ones++;
        }
        index++;
    }
    
    return ones;
};

console.log(`Optimized result for num=6: ${magicalStringOptimized(6)}`);
console.log(`Optimized result for num=10: ${magicalStringOptimized(10)}`);
Optimized result for num=6: 3
Optimized result for num=10: 5

Conclusion

The magical string problem demonstrates self-referential sequences where the pattern describes itself. The key insight is building the string iteratively using previous characters as instructions for generating new ones.

Updated on: 2026-03-15T23:19:00+05:30

553 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements