Magical String

Problem Id: 481 Difficulty: Medium


Intuition

Solution


class Solution:
    def magicalString(self, n: int) -> int:
        """
        1 2 2 1 1 2 1 2 2
        """
        magic = [1, 2, 2]
        index = 2
        one = True
        while len(magic) < n:
            tmp = 1 if one else 2
            if magic[index] == 1:
                magic.append(tmp)
            else:
                magic.append(tmp)
                magic.append(tmp)
            one = not one
            index += 1
        return magic[:n].count(1)