Coordinate Two Threads to Print Odd and Even Numbers in Order

Last updated: November 29, 2026

Quick Overview

Start two threads, one responsible for odd numbers and one for even numbers, so that together they output 1 through n strictly in order.

Google
Software Engineering Fundamentals
Software Engineer
Google
November 29, 2026
Software Engineer
Phone Screen
Software Engineering Fundamentals
Easy

0

0

0 solved


Start two threads, one responsible for odd numbers and one for even numbers, so that together they output 1 through n strictly in order.

A short Google phone screen warm-up that checks whether a candidate can use a condition variable correctly rather than sleeping or busy-waiting. The interviewer looks for a shared predicate, a while-loop wait, and clean termination for both threads.

What the Interviewer Expects
  • Shares one counter protected by a lock
  • Waits on a condition variable inside a while loop
  • Notifies after changing state
  • Ensures both threads exit, including the one waiting when the last number prints
  • Avoids sleeps and busy loops
Key Topics to Cover
condition variable
thread coordination
spurious wakeup
termination
How to Approach This
  1. Apply SOLID principles. Single Responsibility makes code testable, Open/Closed makes it extensible.
  2. Choose data structures based on access patterns, not familiarity.
  3. Prefer immutable data and message passing over shared mutable state for concurrency.
  4. Design APIs with RESTful conventions, versioning, meaningful errors, and pagination from day one.
Possible Follow-up Questions
  • Generalize to k threads printing in round-robin order.
  • How would you do it with two semaphores instead of a condition variable?
  • Why is `notify_all` safer than `notify` here, and when could `notify` be enough?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice System Design Problems
Sample Answer
Requirements
  • Output is exactly 1, 2, ..., n.
  • Thread A emits only odd numbers, thread B only even numbers.
  • Works for n = 0 and n = 1; both threads terminate....
High-Level Design

Shared state is next, the number due to be printed. Each thread waits until next has its parity or exceeds n. When its turn comes it emits, increments, and notifies. The wait predicate includes ...


Submit Your Answer
Markdown supported