1187. Print FooBar Alternately
My accepted Python solution to LeetCode problem 1187, Print FooBar Alternately, running in 65ms.
- Difficulty: Medium
- Python
- Runtime 65ms
- Memory 17.7MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 65ms, memory 17.7MB, accepted 2026-01-02.
from threading import Lock
class FooBar:
def __init__(self, n):
self.n = n
self.foo_lock = Lock()
self.bar_lock = Lock()
self.bar_lock.acquire()
def foo(self, printFoo: 'Callable[[], None]') -> None:
for i in range(self.n):
self.foo_lock.acquire()
printFoo()
self.bar_lock.release()
def bar(self, printBar: 'Callable[[], None]') -> None:
for i in range(self.n):
self.bar_lock.acquire()
printBar()
self.foo_lock.release()