#2715

Timeout Cancellation

Easy
Timeout ManagementFunction Cancellation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution uses a single timeout for the function and a flag to manage cancellation. This approach minimizes the number of timers and checks, making it more efficient and easier to manage.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a variable to track if the function has been cancelled.
  2. 2Step 2: Set a timeout to execute the function fn after t milliseconds.
  3. 3Step 3: Return a cancel function that sets the cancelled flag to true.
solution.py17 lines
1import threading
2
3def cancellable(fn, args, t):
4    cancelled = [False]
5
6    def cancelFn():
7        cancelled[0] = True
8
9    def execute():
10        threading.Timer(t / 1000, lambda: fn(*args) if not cancelled[0] else None).start()
11
12    return cancelFn
13
14# Example usage
15cancelTimeMs = 50
16cancelFn = cancellable(lambda x: x * 5, [2], 20)
17setTimeout(cancelFn, cancelTimeMs)

Complexity note: The time complexity is O(n) since we only set one timeout for the function execution. Space complexity is O(1) as we are not using any additional data structures.

  • 1Using flags for cancellation can simplify logic.
  • 2Minimizing the number of timers improves performance.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.