LeetCode 1114: Print in Order Solution

Master LeetCode problem 1114 (Print in Order), a easy 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.

1114. Print in Order

Problem Explanation

Explanation:

To solve this problem, we can use synchronization mechanisms such as CountDownLatch or Semaphore to ensure that the methods are called in the correct order. We can have a CountDownLatch for each method, and the CountDownLatch of one method will only be released after the previous method has been called. This approach guarantees the correct order of execution.

  1. We initialize three CountDownLatch objects, one for each method: firstLatch, secondLatch, and thirdLatch.
  2. In the first method, we print "first" and then release the secondLatch.
  3. In the second method, we wait for the secondLatch to be released, print "second", and then release the thirdLatch.
  4. In the third method, we wait for the thirdLatch to be released and then print "third".

This approach ensures that the methods are called in the correct order regardless of the scheduling of the threads.

  • Time complexity: O(1) for each method call.
  • Space complexity: O(1).

:

Solution Code

import java.util.concurrent.CountDownLatch;

class Foo {
    private CountDownLatch firstLatch;
    private CountDownLatch secondLatch;

    public Foo() {
        firstLatch = new CountDownLatch(1);
        secondLatch = new CountDownLatch(1);
    }

    public void first() {
        System.out.print("first");
        firstLatch.countDown();
    }

    public void second() throws InterruptedException {
        firstLatch.await();
        System.out.print("second");
        secondLatch.countDown();
    }

    public void third() throws InterruptedException {
        secondLatch.await();
        System.out.print("third");
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1114 (Print in Order)?

This page provides optimized solutions for LeetCode problem 1114 (Print in Order) 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 1114 (Print in Order)?

The time complexity for LeetCode 1114 (Print in Order) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1114 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1114 in Java, C++, or Python.

Back to LeetCode Solutions