Print FooBar Alternately — LeetCode 1115 Python Solution
MediumConcurrency
- Problem
- #1115
- Reading time
- 4 min
- Source
- leetcode.com
The problem
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
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");
}
}
}Python solution
Python
from threading import Semaphore
class FooBar:
def __init__(self, n):
self.n = n
self.f = Semaphore(1)
self.b = Semaphore(0)
def foo(self, printFoo: "Callable[[], None]") -> None:
for _ in range(self.n):
self.f.acquire()
# printFoo() outputs "foo". Do not change or remove this line.
printFoo()
self.b.release()
def bar(self, printBar: "Callable[[], None]") -> None:
for _ in range(self.n):
self.b.acquire()
# printBar() outputs "bar". Do not change or remove this line.
printBar()
self.f.release()Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) auxiliary |
Related problems
Frequently asked questions
- How hard is LeetCode 1115. Print FooBar Alternately?
- LeetCode 1115. Print FooBar Alternately is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1115. Print FooBar Alternately?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1115. Print FooBar Alternately?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1115. Print FooBar Alternately cover?
- LeetCode 1115. Print FooBar Alternately is tagged Concurrency on LeetCode.