Problem 1115

Abstract / Summary

Print foo and bar alternately using two threads that take turns executing.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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;
        }
    }
};
37 lines | 752 bytes | submitted September 4, 2023 | GitHub   11% comment ratio | tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 72% (100k+ submissions).

Typical patterns to solve this problem:
  • Concurrency
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 3 | μ = 3.69 | σ = 1.68

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
24 links | 15 authors | 5 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

4 easy 20 medium
25 solutions   September 4, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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