00:00

Problem Statement

Input/Output Examples

Visual Explanation

signalAll() wakes all waiting threads after each print; the two that are not next simply check the counter and wait again.

Approaches

Both approaches enforce the same rotation. One uses a lock and a shared condition; the other passes a permit around a ring of semaphores.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. The threads are coordinated so strictly that the output is identical on every run (checked over 25 runs); both programs print the same lines.

Complexity Analysis

Here n is the highest number. Each number is printed once; with signalAll(), each step briefly wakes the two threads that are not next.

Interview Tips and Recommended Approach

  • Generalise the rule. For k threads, thread i prints when (n - 1) % k == i.
  • Unlock in finally. Forgetting it can block every thread forever.
  • Compare the tools. Semaphores wake exactly one thread; a shared condition is simpler to generalise.
  • Join the threads before the program exits or reads shared results.

Recommended Approach: ReentrantLock and Condition

Why: it scales to any number of threads by changing one modulus, and it shows how Condition replaces wait()/notify() with explicit locks.