LeetCode 481: Magical String Solution

Master LeetCode problem 481 (Magical String), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

481. Magical String

Problem Explanation

Explanation:

To solve this problem, we will first generate the magical string iteratively. We will start with the given magical string "122" and then iteratively append characters based on the rules mentioned in the problem description. We will keep track of the count of 1's encountered in the generated magical string up to the given input number n.

  • Initialize the magical string with "122" and the count of 1's as 1.
  • Iterate from index 2 to n-1 to generate the magical string.
  • While generating the magical string, we will:
    • Append '1' if the current character is '1' and increment the count of 1's.
    • Append '2' if the current character is '2'.
  • Return the count of 1's up to the given input number n.

Time Complexity: O(n) where n is the given input number.

Space Complexity: O(n) for storing the magical string.

:

Solution Code

class Solution {
    public int magicalString(int n) {
        if (n == 0) {
            return 0;
        }
        if (n <= 3) {
            return 1;
        }
        
        StringBuilder magicalString = new StringBuilder("122");
        int count = 1;
        int index = 2;
        
        while (magicalString.length() < n) {
            char curr = magicalString.charAt(index++);
            char next = (char)('1' + '2' - curr);
            int repeat = magicalString.charAt(magicalString.length() - 1) - '0';
            for (int i = 0; i < repeat; i++) {
                magicalString.append(next);
                if (next == '1') {
                    count++;
                }
                if (magicalString.length() == n) {
                    break;
                }
            }
        }
        
        return count;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 481 (Magical String)?

This page provides optimized solutions for LeetCode problem 481 (Magical String) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 481 (Magical String)?

The time complexity for LeetCode 481 (Magical String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 481 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 481 in Java, C++, or Python.

Back to LeetCode Solutions