Print FooBar Alternately - Problem

You're given a FooBar class that contains two methods: foo() and bar(). Each method runs in a loop n times, printing either "foo" or "bar" respectively.

The challenge is that the same instance of FooBar will be accessed by two different threads simultaneously:

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

Your task is to modify the class to ensure that the output is always "foobar" repeated n times, with proper alternation between the two strings.

Example: If n=3, the expected output should be: foobarfoobarfoobar

This is a classic thread synchronization problem where you need to coordinate two threads to produce alternating output in the correct order.

Input & Output

example_1.py โ€” Basic Case
$ Input: n = 1
โ€บ Output: foobar
๐Ÿ’ก Note: With n=1, foo() runs once printing 'foo', then bar() runs once printing 'bar', resulting in 'foobar'
example_2.py โ€” Multiple Iterations
$ Input: n = 3
โ€บ Output: foobarfoobarfoobar
๐Ÿ’ก Note: With n=3, the pattern 'foobar' repeats 3 times with perfect alternation between the two threads
example_3.py โ€” Edge Case
$ Input: n = 0
โ€บ Output:
๐Ÿ’ก Note: When n=0, neither thread executes their loop, so no output is produced

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Each thread executes n times with minimal synchronization overhead, no busy waiting

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only one mutex, one condition variable, and one boolean state variable needed

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค n โ‰ค 1000
  • Two threads will call foo() and bar() concurrently
  • Output must be exactly 'foobar' repeated n times
  • No other output patterns are acceptable
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 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