C++ 1115.cpp
class FooBar {
private:
int n;
volatile int state; // brute-force it ...
public:
FooBar(int n) {
this->n = n;
state = 0;
}
void foo(function<void()> printFoo) {
for (int i = 0; i < n; i++) {
while (state != 0);
state = 0;
// printFoo() outputs "foo". Do not change or remove this line.
printFoo();
state = 1;
}
}
void bar(function<void()> printBar) {
for (int i = 0; i < n; i++) {
while (state != 1);
state = 1;
// printBar() outputs "bar". Do not change or remove this line.
printBar();
state = 0;
}
}
};
Difficulty
and has an acceptance rate of about 72% (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 simple coordination mechanism between two threads that repeatedly invoke foo and bar. The constructor stores the iteration count n and initializes a shared state variable. The two public member functions, foo and bar, each contain a loop that runs exactly n times. Within each iteration the functions spin on the state variable until it reaches the expected value, perform the supplied printing operation, and then toggle state to allow the counterpart thread to proceed. The design relies on busy-waiting and a volatile qualifier to ensure visibility of state across threads.
Key Steps
Construction
FooBar(int n) {
this->n = n;
state = 0;
}
The constructor captures the number of required alternations and sets the initial synchronization flag to 0. This initial value permits the foo thread to execute first because it waits for state to be 0.
Foo Thread Logic
void foo(function<void()> printFoo) {
for (int i = 0; i < n; i++) {
while (state != 0);
state = 0;
// printFoo() outputs "foo". Do not change or remove this line.
printFoo();
state = 1;
}
}
Each iteration begins with a spin-wait that blocks until state equals 0. Once the condition is satisfied the thread explicitly writes 0 back to state (a redundant assignment that reinforces the expected value). The supplied printFoo callback is then invoked, after which state is set to 1 to signal the bar thread that it may proceed.
Bar Thread Logic
void bar(function<void()> printBar) {
for (int i = 0; i < n; i++) {
while (state != 1);
state = 1;
// printBar() outputs "bar". Do not change or remove this line.
printBar();
state = 0;
}
}
The bar function mirrors the structure of foo. It spins until state becomes 1, writes 1 back to the variable, calls the printBar callback, and finally resets state to 0 to hand control back to the foo thread.
Edge Cases Handled
When the iteration count n is zero, both loops execute zero times. The constructor still initializes state to 0, ensuring that no thread attempts to enter a spin-wait that could never be satisfied. The spin-wait condition itself tolerates any intermediate values of state because the loops only proceed when the exact expected value appears. The use of volatile guarantees that even if a thread experiences a context switch, the most recent write to state will be observed by the other thread, preventing indefinite blocking.
The explicit assignments state = 0 inside foo and state = 1 inside bar act as safeguards against spurious reads that might occur due to compiler optimizations. By writing the expected value back before invoking the callback, the code ensures that the synchronization flag remains consistent even if the callback itself performs operations that could affect memory ordering.
Performance Optimizations
The implementation avoids heavyweight synchronization primitives such as mutexes or condition variables. By using a single volatile integer and busy-waiting, the overhead per iteration is limited to a simple load-compare loop and a few store instructions. This approach eliminates kernel transitions and lock contention, which can be advantageous when the number of alternations n is small and the threads are expected to run on the same core.
The choice of a plain integer for state enables the compiler to generate minimal machine code for the comparison and assignment operations. The spin-wait loops are tight and benefit from modern processors’ branch prediction and speculative execution, reducing the latency of each synchronization point.
Because the two threads strictly alternate, there is no need for additional bookkeeping or queue structures. The deterministic hand-off pattern ensures that each thread performs exactly one store to state per iteration, minimizing memory traffic and cache line bouncing. The volatile qualifier, while preventing certain compiler optimizations, still allows the processor to keep the variable in a cache line, preserving fast access while guaranteeing visibility across cores.
ELI5 - Simplified Explanation
Imagine there are two robots named Foo and Bar who want to build a tower together. They take turns picking up blocks so the tower stays straight. The code uses a special tracker called state to keep them in order.
The first robot, Foo, looks at the tracker. If the tracker says zero, it knows it is time to work. Foo prints out its name and then changes the tracker to one. This tells the other robot that it is his turn now. While Foo is waiting, it just watches the tracker over and over to see if the number has changed.
The second robot, Bar, does almost the same thing. It looks at the tracker, but it waits until the number is one. Once the tracker says one, Bar prints its name and then changes the tracker back to zero. This sends the signal back to Foo that it is time for another turn.
They keep repeating this dance until they have finished all the work. By watching the little number in the tracker, they make sure they never try to work at the exact same time and always follow the right 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 | Python | C++ | Java | TS | |
| WalkCCC | Python | C++ | Java | |||
| leetcode.ca | Python | C++ | Java | |||
| Progiez | Python | C++ | Java | |||
| github | black-shadows | C++ | ||||
| chandansgowda | Python | |||||
| 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++ | |||||
| chandansgowda | Python | |||||
| charles-wangkai | Java | |||||
| DimitrisJim | Python | |||||
| fsq | C++ | |||||
| keineahnung2345 | C++ | |||||
| Krazune | Java | |||||
| lkwq007 | Python | |||||
| suxrobGM | C# | |||||
| trung-hn | Python | |||||
| varunu28 | Java |
Videos
Similar Problems
- problem 1114: Print in Order
- problem 1116: Print Zero Even Odd
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 1116: Print Zero Even Odd
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