Python 0481.py
class Solution:
def magicalString(self, n: int) -> int:
# understanding the problem: 30 minutes
# writing the code: 5 minutes
# that's ridiculous ...
# by the way:
# https://en.wikipedia.org/wiki/Kolakoski_sequence
# https://oeis.org/A156077 and https://oeis.org/A000002
sequence = [ 1, 2, 2 ]
pos = 2
while len(sequence) < n:
last = sequence[-1]
length = sequence[pos]
pos += 1
sequence += [ last ^ 3 ] * length # same as 3 - last, but looks nicer to me :-)
# maybe we need to strip trailing elements
while len(sequence) > n:
sequence.pop()
return sequence.count(1)
Difficulty
and has an acceptance rate of about 52% (80k+ submissions).
Typical patterns to solve this problem:
- String
- Two Pointers
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The magicalString method generates the prefix of the Kolakoski-type magical string up to length n and returns the number of occurrences of the digit 1 in that prefix. The implementation builds the sequence iteratively, using the already generated part to dictate how many copies of the opposite digit should be appended. After the sequence reaches or exceeds the desired length, any excess elements are removed, and the built-in count method yields the final answer.
Key Steps
Initialization
sequence = [1, 2, 2]
pos = 2
The algorithm starts with the known seed of the magical string, [1, 2, 2]. The variable pos points to the element that determines the run length for the next block of digits.
Generation Loop
while len(sequence) < n:
last = sequence[-1]
length = sequence[pos]
pos += 1
sequence += [last ^ 3] * length # same as 3 - last
Inside the loop the most recent digit (last) is retrieved. The element at index pos supplies the number of times the opposite digit must be repeated (length). The pointer pos is advanced so that the next iteration reads the following run-length indicator. The expression last ^ 3 flips 1 to 2 and 2 to 1 without a conditional branch, and the list multiplication [last ^ 3] * length creates the required block in a single operation, which is then concatenated to sequence.
Truncation Loop
while len(sequence) > n:
sequence.pop()
If the generation step overshoots the target length, the excess elements are removed one by one from the end of the list. This ensures that the final sequence length is exactly n.
Counting Result
return sequence.count(1)
The built-in count method scans the list once and returns the total number of 1s, which is the required output.
Edge Cases
When n is zero the initial list is trimmed by the truncation loop until it becomes empty, and count(1) correctly yields 0. For n equal to one, two, or three the algorithm never enters the generation loop; the truncation loop removes any surplus elements beyond n, leaving the appropriate prefix of the seed. Because the generation loop condition checks len(sequence) < n, the code never attempts to read beyond the bounds of sequence when n is small. The use of pop in the truncation phase gracefully handles any overshoot without raising an exception.
Performance Optimizations
The most noticeable optimization is the use of list multiplication to create a block of identical digits in a single step, which avoids repeated append calls and reduces interpreter overhead. The XOR trick (last ^ 3) computes the complementary digit without branching, allowing the interpreter to execute a straightforward arithmetic operation instead of a conditional expression. Extending the list with += performs an in-place concatenation, minimizing the number of intermediate objects. Finally, the final count is performed by the highly optimized C implementation of list.count, which is faster than a manual Python loop.
ELI5 - Simplified Explanation
Imagine you have a magical row of building blocks that likes to grow all by itself. We start with three blocks arranged as one, two, two. These numbers tell us how many blocks we should add next. The last block in our row says what number to use, and our special rule swaps ones for twos and twos for ones. If the last block is a one, it tells us to add twos, and if it is a two, it tells us to add ones. We look at the next number in our row to know how many times to add that new block. The row keeps growing this way until it is as long as we want it to be. Once the row reaches the size requested, we count how many blocks are labeled with a one.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | Python | ||||||
| leetcode.ca | C++ | Rust | Java | Go | Python | TS | |||
| LeetcodeHelp | C++ | Java | Python | ||||||
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| JoshCrozier | JS | ||||||||
| linouk23 | C++ | ||||||||
| lzl124631x | C++ | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| zfang399 | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| JoshCrozier | JavaScript | ||||||||
| linouk23 | C++ | ||||||||
| lzl124631x | C++ | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| zfang399 | C++ |
Videos
Solved On The Same Day
- problem 467: Unique Substrings in Wraparound String
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality