My Simple and Fast Swift Solution


  • 0
    Y
    func magicalString(_ n: Int) -> Int {
            var magicArray:[Int] = [1,2,2]
            var count = 0
            var i = 2
            while i < n{
                let j = magicArray.last   // last number
                for i in 0..<magicArray[i]{
                    magicArray.append(j==1 ? 2 : 1)
                }
                i+=1
            }
            for i in 0..<n{
                if magicArray[i] == 1{
                    count += 1
                }
            }
            return count
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.