Print in Order — LeetCode 1114 Python Solution

EasyConcurrency
Problem
#1114
Reading time
4 min

The problem

Suppose we have a class: public class Foo { public void first() { print("first"); } public void second() { print("second"); } public void third() { print("third"); } } The same instance of Foo will be passed to three different threads. Thread A will call first(), thread B will call second(), and thread C will call third().

Example

public class Foo {
  public void first() { print("first"); }
  public void second() { print("second"); }
  public void third() { print("third"); }
}

Python solution

Python
class Foo:
    def __init__(self):
        self.l2 = threading.Lock()
        self.l3 = threading.Lock()
        self.l2.acquire()
        self.l3.acquire()

    def first(self, printFirst: 'Callable[[], None]') -> None:
        printFirst()
        self.l2.release()

    def second(self, printSecond: 'Callable[[], None]') -> None:
        self.l2.acquire()
        printSecond()
        self.l3.release()

    def third(self, printThird: 'Callable[[], None]') -> None:
        self.l3.acquire()
        printThird()

Complexity

MeasureComplexity
TimeO(1)
SpaceO(1) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 1114. Print in Order?
LeetCode 1114. Print in Order is rated Easy on LeetCode.
What is the time complexity of LeetCode 1114. Print in Order?
The Python solution on this page runs in O(1).
What is the space complexity of LeetCode 1114. Print in Order?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1114. Print in Order cover?
LeetCode 1114. Print in Order is tagged Concurrency on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview