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 Semaphore Synchronization Approach INPUT Thread A Thread B foo() bar() Input Parameter n = 1 FooBar Class class FooBar { void foo() // prints "foo" void bar() // prints "bar" } ALGORITHM STEPS 1 Initialize Semaphores fooSem=1, barSem=0 2 foo() acquires fooSem Print "foo", release barSem 3 bar() acquires barSem Print "bar", release fooSem 4 Repeat n times Alternating execution Semaphore Flow fooSem barSem signal signal alternates FINAL RESULT Execution Timeline foo bar t=0 t=1 Output String "foobar" OK - Alternating! For n=1: output once For n=2: foobarfoobar Key Insight: Semaphores ensure mutual exclusion. fooSem starts at 1 (foo goes first), barSem starts at 0 (bar waits). Each thread releases the other's semaphore after printing, creating a perfect ping-pong alternation pattern. TutorialsPoint - Print FooBar Alternately | Semaphore Synchronization
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