Problem 1114

Abstract / Summary

Print three methods in the order they are called using a single print statement.

Note

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

C++ 1114.cpp

class Foo {
        volatile int state;
public:
    Foo() {
        state = 1;
    }

    void first(function<void()> printFirst) {
        // printFirst() outputs "first". Do not change or remove this line.
        printFirst();

        state++;
    }

    void second(function<void()> printSecond) {
        while (state != 2);

        // printSecond() outputs "second". Do not change or remove this line.
        printSecond();

        state++;
    }

    void third(function<void()> printThird) {
        while (state != 3);

        // printThird() outputs "third". Do not change or remove this line.
        printThird();
    }
};

30 lines | 672 bytes | submitted August 8, 2023 | GitHub   15% comment ratio | tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 73% (300k+ 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 class Foo coordinates three actions-first, second, and third-so that they are executed in a strict order regardless of the order in which the corresponding member functions are invoked from different threads. A single integer field, declared as volatile, serves as the shared state that all threads observe. The constructor initializes this state, and each method updates or waits on the state to enforce the required sequencing.

Constructor

The constructor sets the initial state to 1, indicating that the first action is ready to run.

Foo() {
    state = 1;
}

Because state is volatile, the write is immediately visible to any thread that subsequently reads the variable.

first Method

first receives a callable that prints the word “first”. The method invokes the callable, then increments the shared state to signal that the first step has completed.

void first(function<void()> printFirst) {
    // printFirst() outputs "first". Do not change or remove this line.
    printFirst();

    state++;
}

The increment changes the state from 1 to 2, allowing the second method to proceed.

second Method

second begins by busy-waiting until the shared state equals 2. This loop blocks the thread until the first method has performed its increment. Once the condition is satisfied, the method calls the supplied printable function and then increments the state to 3.

void second(function<void()> printSecond) {
    while (state != 2);

    // printSecond() outputs "second". Do not change or remove this line.
    printSecond();

    state++;
}

The waiting loop relies on the volatile qualifier to guarantee that each read of state reflects the most recent write from another thread.

third Method

third also uses a busy-wait, this time for the state to become 3. When the condition is met, it invokes the provided printable function. No further state change is required because this is the final step.

void third(function<void()> printThird) {
    while (state != 3);

    // printThird() outputs "third". Do not change or remove this line.
    printThird();
}

Edge Cases

The implementation gracefully handles the situation where the methods are called out of order. If second or third are invoked before the preceding step has completed, each method’s while-loop will spin until the expected state value appears, effectively serializing the execution without deadlocking. The use of a volatile integer ensures that even if a thread experiences a context switch or runs on a different core, it will observe the most recent state value.

Another implicit edge case is the scenario where the same method is called multiple times from different threads. Because each method increments the state only after its own printable action, subsequent calls will find the state already advanced and will either proceed immediately (if the state matches) or continue spinning until the state reaches the required value. This behavior prevents premature execution of later steps.

Performance Considerations

The primary performance characteristic stems from the busy-waiting loops in second and third. By continuously reading the volatile variable, the code avoids the overhead of kernel-level synchronization primitives such as mutexes or condition variables. For short waiting periods, this can be more efficient because it eliminates context switches and kernel scheduling latency.

Incrementing an int is an atomic operation on most modern architectures when the variable is aligned, and the volatile qualifier prevents the compiler from caching the value in a register. This ensures that each read reflects the latest write, allowing the spin loops to detect state changes promptly.

Because the state transitions are monotonic (1 → 2 → 3) and each transition occurs exactly once, the loops terminate quickly after the preceding step finishes, limiting the amount of wasted CPU cycles. The overall design therefore achieves ordering with minimal synchronization scaffolding while keeping the runtime overhead low for the intended use case.

written by openai gpt

ELI5 - Simplified Explanation

Think of this code like three friends who want to take turns playing a game in a specific order. The friend named first goes right away because they are ready. They have a little counter called state that starts at one. After the first friend finishes, they change the counter to two so the next person knows it is time. The second friend is waiting patiently and keeps checking the counter over and over again. As soon as the counter becomes two, the second friend knows it is their turn to play, and when they finish, they change the counter to three. The third friend is also waiting and watching the counter. They do not do anything until the counter reaches three, which shows that the first two friends are done. Once the counter hits three, the third friend finally gets to play their part. This makes sure that even though they are all different parts of the program, they follow the right order every single time.

written by google gemini

Code Quality

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

Complexity Analysis

not analyzed yet

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 C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis C++
fsq C++
keineahnung2345 C++
Krazune Java
lkwq007 Python
suxrobGM C#
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Java, Python, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis C++
fsq C++
keineahnung2345 C++
Krazune Java
lkwq007 Python
suxrobGM C#
varunu28 Java
25 links | 16 authors | 6 languages

Videos

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

Similar Problems

1 similar problem

Solved On The Same Day

18 easy 43 medium 2 hard
64 solutions   August 8, 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