Leetcode 481. Magical String

Problem Explanation

This problem is a string manipulation problem, involves generating a magical string and count the number of '1's in it up to a certain length. The magical string consists of only '1' and '2', and it obeys the rules such that the concatenation of the number of contiguous occurrences of '1's and '2's creates the string itself. The first few elements are S = "1221121221221121122", this pattern continues indefinitely.

The task is to, given an integer N representing the length of the string, return the number of '1's in the first N elements of the magical string.

Let's take an example:


Input: 6

Output: 3

The first 6 elements of the magical string S are "122112" and it contains three '1's, so the output is 3.

Solution Approach

The solution uses a string to generate the magical string up to a length of N. This string is initially set as " 122".

Next, a loop is started from the 3rd index till N. If the current index is odd, append to the string (s[i] - '0') number of '1's. But if it is even, append to the string (s[i] - '0') number of '2's.

Finally, return the count of '1's in the first N+1 characters of the string.

We can observe that, the number of next character to be appended depends on the value of the current character, and whether the index is odd or even determines what character ('1' or '2') is to be appended.


3class Solution:
4    def magicalString(self, n: int) -> int:
5        s = '122'
7        # Generate the magical string s up to length n
8        for i in range(2, n):
9            s += int(s[i]) * ('1' if len(s) % 2 else '2')
11        return s[:n].count('1')


3public class Solution {
4    public int magicalString(int n) {
5        String s = "122";
7        for (int i = 2; i < n; ++i)
8            s += new String(new char[s.charAt(i) - '0']).replace("\0", (s.length() % 2 == 0) ? "2" : "1");
10        return (int)s.chars().limit(n).filter(c -> c == '1').count();
11    }


3class Solution {
4    magicalString(n) {
5        let s = "122";
7        for (let i = 2; i < n; ++i)
8            s += Array(s[i]-'0').fill((s.length % 2 == 0) ? '2' : '1').join("");
10        return s.slice(0, n).split('1').length - 1;
11    }


3class Solution {
5    int magicalString(int n) {
6        string s = "122";
8        for (int i = 2; i < n; ++i)
9            s += string(s[i]-'0', (s.size() % 2 == 0) ? '2' : '1');
11        return count(s.begin(), next(s.begin(), n), '1');
12    }


3public class Solution {
4    public int MagicalString(int n) {
5        string s = "122";
7        for (int i = 2; i < n; ++i)
8            s += new String((s.Length % 2 == 0) ? '2' : '1', s[i] - '0');
10        return s.Take(n).Count(c => c == '1');
11    }

Time Complexity

The time complexity of this solution is O(n) since we perform a single pass through the string up to length n.# Space Complexity

In terms of space complexity, the same also equals O(n) as we are constructing the string up to length n. Therefore, the space used by this algorithm is essentially proportional to the input size.

Pros and Cons

The solution performs well in terms of time and space complexity. The only issue could be the string handling and creating new strings repeatedly which can be compute-heavy for languages like Java or Python. This could be optimized by using a data structure such as LinkedList or StringBuilder depending on the language used.

For languages like JavaScript that handle string concatenation more efficiently, this might not be a significant problem.

This particular problem can also be seen as an interesting application of self-referential sequences and thus, can also be solved by other sequence generation algorithms.


This problem tests understanding of string manipulations and the ability to identify and generate self-referential sequences. The tasks can be broken down into creating the sequence, ensuring the pattern is maintained, and finally counting the occurrence of a given character, in this case, '1'. Understanding the rules of generation of the magical string is key to figuring out the solution.

Different programming languages can be leveraged to solve it using string manipulations and sequence generation and computations.

The solution is quite efficient friendly, with a time and space complexity of O(n), making it suitable for large inputs.

Got a question? Ask the Teaching Assistant anything you don't understand.

Still not clear? Ask in the Forum,  Discord or Submit the part you don't understand to our editors.

TA 👨‍🏫