Magical String — LeetCode 481 Python Solution

MediumTwo PointersString
Problem
#481
Reading time
2 min

The problem

A magical string s consists of only '1' and '2' and obeys the following rule: Concatenating the sequence of lengths of its consecutive groups of identical characters '1' and '2' generates the string s itself. The first few elements of s is s = "1221121221221121122……".

Example

Input
n = 6
Output
3
Explanation
The first 6 elements of magical string s is "122112" and it contains three 1's, so return 3.

Python solution

Python
class Solution:
    def magicalString(self, n: int) -> int:
        s = [1, 2, 2]
        i = 2
        while len(s) < n:
            pre = s[-1]
            cur = 3 - pre
            s += [cur] * s[i]
            i += 1
        return s[:n].count(1)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 481. Magical String is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 481. Magical String?
LeetCode 481. Magical String is rated Medium on LeetCode.
What is the time complexity of LeetCode 481. Magical String?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 481. Magical String?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 481. Magical String cover?
LeetCode 481. Magical String is tagged Two Pointers and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview