Talentd
FleetCode

1115. Print FooBar Alternately

Medium67.7% acceptance

Suppose you are given the following code:

class FooBar {
  public void foo() {
    for (int i = 0; i < n; i++) {
      print("foo");
    }
  }

  public void bar() {
    for (int i = 0; i < n; i++) {
      print("bar");
    }
  }
}

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

  • thread A will call foo(), while
  • thread B will call bar().

Modify the given program to output "foobar" n times.

Example 1:

Input: n = 1
Output: "foobar"
Explanation: There are two threads being fired asynchronously. One of them calls foo(), while the other calls bar().
"foobar" is being output 1 time.

Example 2:

Input: n = 2
Output: "foobarfoobar"
Explanation: "foobar" is being output 2 times.

Constraints:

  • 1 <= n <= 1000
7:21
Still stuck?Read 3 approaches, or watch a walkthrough.
Open solution
Loading editor…
1class FooBar:
2 def __init__(self, n):
3 self.n = n
4
5
6 def foo(self, printFoo: 'Callable[[], None]') -> None:
7
8 for i in range(self.n):
9
10 # printFoo() outputs "foo". Do not change or remove this line.
11 printFoo()
12
13
14 def bar(self, printBar: 'Callable[[], None]') -> None:
15
16 for i in range(self.n):
17
18 # printBar() outputs "bar". Do not change or remove this line.
19 printBar()
Starter codePython 3Spaces: 4
Examples
Input
1
Input
2
Your code is saved on this device.Solution