#481

Magical String

Medium
Two PointersStringTwo PointersDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution builds the magical string iteratively while counting '1's, avoiding the need to store the entire string. This approach is efficient and directly addresses the problem requirements.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize an array to hold the counts of '1's and '2's, starting with the first character '1'.
  2. 2Step 2: Use a pointer to track the current position and another to determine how many characters to add based on the last character.
  3. 3Step 3: Continue this process until the length of the magical string reaches n, counting '1's as you go.
  4. 4Step 4: Return the count of '1's after reaching n.
solution.py19 lines
1# Full working Python code
2
3def magical_string(n):
4    if n == 1:
5        return 1
6    s = [1]
7    count_ones = 1
8    index = 0
9    for i in range(1, n):
10        next_char = 2 if s[-1] == 1 else 1
11        for _ in range(s[index]):
12            if len(s) < n:
13                s.append(next_char)
14                if next_char == 1:
15                    count_ones += 1
16        index += 1
17    return count_ones
18
19print(magical_string(6))  # Output: 3

Complexity note: The time complexity is O(n) because we only traverse the string once while building it, and the space complexity is O(n) due to storing the characters in an array.

  • 1The magical string is generated based on the counts of previous characters, making it recursive in nature.
  • 2Understanding the pattern of how '1's and '2's are added is crucial for optimizing the solution.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.