Print FooBar Alternately - Problem

You are given a FooBar class with two methods:

  • foo() - prints "foo" n times
  • bar() - prints "bar" n times

The same instance of FooBar will be passed to two different threads:

  • Thread A will call foo()
  • Thread B will call bar()

Your task: Modify the program so that the output is "foobar" repeated n times (alternating "foo" and "bar").

For example, if n = 3, the output should be: foobarfoobarfoobar

Input & Output

Example 1 — Basic Case
$ Input: n = 1
Output: foobar
💡 Note: Thread A prints 'foo' once, Thread B prints 'bar' once, alternating to produce 'foobar'
Example 2 — Multiple Iterations
$ Input: n = 2
Output: foobarfoobar
💡 Note: Pattern repeats: foo-bar-foo-bar, creating 'foobarfoobar'
Example 3 — Larger Input
$ Input: n = 3
Output: foobarfoobarfoobar
💡 Note: Three complete alternations: foo-bar-foo-bar-foo-bar

Constraints

  • 1 ≤ n ≤ 1000
  • The same instance of FooBar is passed to two different threads
  • Thread A calls foo(), Thread B calls bar()
  • Output must be exactly 'foobar' repeated n times

Visualization

Tap to expand
Print FooBar Alternately Problem (n=2)Thread Acalls foo()Thread Bcalls bar()foobarfoobarSynchronized Output: foobarfoobarChallenge: Ensure perfect alternation without race conditions
Understanding the Visualization
1
Input
n=2 (repeat foobar 2 times)
2
Process
Thread A prints foo, Thread B prints bar, alternating
3
Output
foobarfoobar (perfect alternation)
Key Takeaway
🎯 Key Insight: Thread synchronization is essential to prevent race conditions and ensure correct alternating output
Asked in
Facebook 35 Amazon 28 Google 22 Microsoft 18
28.4K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen