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.

  1. Initialize two semaphores: semaphoreFoo initialized with 1 (to allow the first thread to start) and semaphoreBar initialized with 0.
  2. In the foo method, acquire the semaphore semaphoreFoo, print "foo", release semaphoreBar.
  3. In the bar method, acquire the semaphore semaphoreBar, print "bar", release semaphoreFoo.

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.

Back to LeetCode Solutions