Print FooBar Alternately - Problem
You are given a FooBar class with two methods:
foo()- prints "foo" n timesbar()- 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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code