LeetCode 1115: Print FooBar Alternately Solution
Master LeetCode problem 1115 (Print FooBar Alternately), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1115. Print FooBar Alternately
Problem Explanation
Explanation:
To solve this problem, we can use a synchronization mechanism such as Semaphore to control the execution of the two threads (foo and bar). We can use two semaphores, one to control the execution of foo and the other to control the execution of bar. By coordinating these semaphores, we can ensure that "foobar" is printed alternately n times.
- Initialize two semaphores:
semaphoreFooinitialized with 1 (to allow the first thread to start) andsemaphoreBarinitialized with 0. - In the
foomethod, acquire the semaphoresemaphoreFoo, print "foo", releasesemaphoreBar. - In the
barmethod, acquire the semaphoresemaphoreBar, print "bar", releasesemaphoreFoo.
Time complexity: O(n) where n is the input value. Space complexity: O(1)
Solution Code
class FooBar {
private int n;
private Semaphore semaphoreFoo = new Semaphore(1);
private Semaphore semaphoreBar = new Semaphore(0);
public FooBar(int n) {
this.n = n;
}
public void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n; i++) {
semaphoreFoo.acquire();
printFoo.run();
semaphoreBar.release();
}
}
public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; i++) {
semaphoreBar.acquire();
printBar.run();
semaphoreFoo.release();
}
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1115 (Print FooBar Alternately)?
This page provides optimized solutions for LeetCode problem 1115 (Print FooBar Alternately) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1115 (Print FooBar Alternately)?
The time complexity for LeetCode 1115 (Print FooBar Alternately) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1115 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1115 in Java, C++, or Python.