C++ 1116.cpp
class ZeroEvenOdd {
private:
atomic<int> limit, current;
atomic<int> state;
public:
ZeroEvenOdd(int n) {
limit = n;
current = 0;
state = 0;
}
// printNumber(x) outputs "x", where x is an integer.
void zero(function<void(int)> printNumber) {
while (current < limit)
if (state % 2 == 0)
{
printNumber(0);
state++;
}
}
void even(function<void(int)> printNumber) {
while (current < limit)
if (state == 3)
{
printNumber(++current);
state = 0;
}
}
void odd(function<void(int)> printNumber) {
while (current < limit)
if (state == 1)
{
printNumber(++current);
state = 2;
}
}
};
Difficulty
and has an acceptance rate of about 65% (100k+ submissions).
Typical patterns to solve this problem:
- Concurrency
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 presented class implements a coordinated printing scheme where three threads cooperate to output a sequence that alternates a zero with successive integers, separating odd and even numbers into distinct execution paths. The design relies on three atomic members to maintain shared state without explicit locks, enabling lock-free synchronization across the zero, odd, and even methods. Construction initializes the shared counters and the state machine that drives the ordering of prints.
Core Components
Atomic State Variables
The class declares three atomic integers:
atomic<int> limit, current;
atomic<int> state;
limit stores the target count supplied at construction, current tracks the most recently printed integer, and state encodes the next expected action in the cycle. Because they are atomic, reads and writes are guaranteed to be observed consistently across threads, eliminating data races while avoiding heavyweight mutexes.
Constructor Initialization
During construction the members receive their initial values:
ZeroEvenOdd(int n) {
limit = n;
current = 0;
state = 0;
}
Setting state to zero positions the system to begin with the zero-printing thread, while current starts at zero so that the first increment yields the integer one.
Execution Flow
Zero-Printing Thread
The zero method loops while the shared current counter remains below the target limit. Inside the loop it checks whether the state indicates that a zero should be printed:
while (current < limit)
if (state % 2 == 0)
{
printNumber(0);
state++;
}
The modulo test treats even values of state (0 and 2) as signals that the zero thread may emit a zero. After printing, the state is incremented, advancing the cycle to the next expected thread.
Odd-Printing Thread
The odd method also iterates while current is less than limit. It proceeds only when the state equals one, which follows a zero print:
while (current < limit)
if (state == 1)
{
printNumber(++current);
state = 2;
}
Here the pre-increment of current yields the next odd integer, and the state is set to two, preparing the system for the subsequent zero output.
Even-Printing Thread
The even method mirrors the odd thread but reacts to a state value of three:
while (current < limit)
if (state == 3)
{
printNumber(++current);
state = 0;
}
After printing the next even integer, the state resets to zero, completing the cycle and allowing the zero thread to start the next round.
Edge Cases Handled
When the supplied limit is zero, the condition current < limit is false from the outset, causing each thread’s loop to terminate immediately without performing any prints. This prevents unnecessary work and respects the contract of producing no output for an empty sequence.
The modulo operation in the zero thread (state % 2 == 0) gracefully accommodates both the initial state (0) and the state after an odd number has been printed (2). This ensures that the zero thread can correctly resume after either an odd or an even number, preserving the intended alternating pattern.
The state transitions are designed so that the system never attempts to print beyond the limit. Each increment of current occurs only after confirming that current is still below limit, guaranteeing that the final integer printed does not exceed the requested count.
Performance Optimizations
The implementation leverages atomic variables to achieve lock-free coordination, which reduces context-switch overhead compared to traditional mutex-based solutions. By using simple integer checks and increments, the critical path consists of lightweight operations that are inexpensive on modern processors.
The state machine is encoded in a single integer, allowing each thread to make a single comparison to decide whether it should act. This minimizes branching and keeps the hot loop tight, which is beneficial for CPU pipeline efficiency.
Because the loops are driven by the shared current counter, each thread exits promptly once the target is reached, avoiding lingering spin-wait after completion. The use of pre-increment (++current) directly updates the shared counter while also providing the value to print, eliminating the need for a separate read-modify-write sequence.
Overall, the design emphasizes minimal synchronization primitives, compact state representation, and straightforward control flow, all of which contribute to efficient concurrent execution.
ELI5 - Simplified Explanation
Imagine a busy playground with three little robots who want to count numbers together. There is one robot whose whole job is to say the number zero, another robot who loves saying odd numbers like one and three, and a third robot who loves saying even numbers like two and four.
These three robots have a special rulebook called state that helps them take turns. When the first robot sees that the rulebook says zero, it shouts out the number zero and then changes the rulebook so it is the turn for someone else.
Then, the other robots look at the rulebook. If the rulebook says it is time for an odd number, the odd robot gets excited, counts up by one, and shouts out the new number. After that, it changes the rulebook again so the zero robot can go back to work.
If the rulebook says it is time for an even number, the even robot waits for its special moment, counts up by one, and shouts out the next even number. It also updates the rulebook so the zero robot can have another turn.
They keep doing this dance over and over again, peeking at the rulebook to see if it is their turn to speak, until they reach the top number they agreed to count up to. It is just like a relay race where everyone knows exactly when to jump in so they can tell the story of the numbers in the perfect order.
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++ | Python | Java | TS | |
| WalkCCC | C++ | Python | Java | |||
| leetcode.ca | C++ | Python | Java | |||
| Progiez | C++ | Python | Java | |||
| github | black-shadows | C++ | ||||
| charles-wangkai | Java | |||||
| DimitrisJim | Python | |||||
| fsq | C++ | |||||
| keineahnung2345 | C++ | |||||
| Krazune | Java | |||||
| lkwq007 | Python | |||||
| suxrobGM | C# | |||||
| trung-hn | Python | |||||
| varunu28 | Java | |||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||
| WalkCCC | C++, Python, Java | |||||
| leetcode.ca | C++, Java, Python | |||||
| Progiez | C++, Java, Python | |||||
| black-shadows | C++, C++ | |||||
| charles-wangkai | Java | |||||
| DimitrisJim | Python | |||||
| fsq | C++ | |||||
| keineahnung2345 | C++ | |||||
| Krazune | Java | |||||
| lkwq007 | Python | |||||
| suxrobGM | C# | |||||
| trung-hn | Python | |||||
| varunu28 | Java |
Videos
Similar Problems
- problem 1115: Print FooBar Alternately
- problem 1195: Fizz Buzz Multithreaded
Solved On The Same Day
- problem 292: Nim Game
- problem 572: Subtree of Another Tree
- problem 617: Merge Two Binary Trees
- problem 671: Second Minimum Node In a Binary Tree
- problem 152: Maximum Product Subarray
- problem 207: Course Schedule
- problem 210: Course Schedule II
- problem 211: Design Add and Search Words Data Structure
- problem 213: House Robber II
- problem 237: Delete Node in a Linked List
- problem 260: Single Number III
- problem 416: Partition Equal Subset Sum
- problem 437: Path Sum III
- problem 450: Delete Node in a BST
- problem 560: Subarray Sum Equals K
- problem 606: Construct String from Binary Tree
- problem 623: Add One Row to Tree
- problem 652: Find Duplicate Subtrees
- problem 654: Maximum Binary Tree
- problem 655: Print Binary Tree
- problem 662: Maximum Width of Binary Tree
- problem 669: Trim a Binary Search Tree
- problem 687: Longest Univalue Path
- problem 1115: Print FooBar Alternately
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