00:00

Problem Statement

Input/Output Examples

Visual Explanation

Waiting inside a while loop, not an if, protects against spurious wake-ups and against being woken when it is still not your turn.

Approaches

Both approaches enforce strict turns. One uses a lock with wait()/notifyAll(); the other passes permits between two 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 printed. Each number is printed once; the threads spend the rest of the time blocked, not spinning.

Interview Tips and Recommended Approach

  • Always wait in a loop. if (notMyTurn) wait(); breaks on spurious wake-ups.
  • Use notifyAll() unless you are sure only the right thread can be waiting.
  • Plan termination. The last thread to finish must wake the other one, or it waits forever.
  • Know the modern tools. Semaphores or ReentrantLock conditions make the hand-over more explicit.

Recommended Approach: wait() and notifyAll()

Why: it shows the fundamentals of thread communication, monitors, waiting and notification, which is what this interview question tests.