Problem 1116

Abstract / Summary

Multiple threads print numbers in order zero even odd using a shared variable to coordinate their output.

Note

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

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;
            }
    }
};
40 lines | 914 bytes | submitted September 4, 2023 | GitHub   2% comment ratio | tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 65% (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 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.

written by openai gpt

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.

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 | μ = 3.74 | σ = 1.94

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 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
23 links | 14 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

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