#2725

Interval Cancellation

Easy
Timer FunctionsAsynchronous Programming
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(n)

The optimal solution uses setInterval to repeatedly call the function at the specified interval until the cancellation time is reached. This approach is efficient and leverages JavaScript's built-in timing functions.

⚙️

Algorithm

3 steps
  1. 1Step 1: Call the function fn with the provided args immediately and store the result.
  2. 2Step 2: Use setInterval to call fn every t milliseconds.
  3. 3Step 3: Use setTimeout to clear the interval after cancelTimeMs.
solution.py13 lines
1import time
2
3def cancellable(fn, args, t, cancelTimeMs):
4    results = []
5    results.append({'time': 0, 'returned': fn(*args)})
6    def call_fn():
7        results.append({'time': int(time.time() * 1000), 'returned': fn(*args)})
8    timer = time.time()
9    while time.time() < timer + cancelTimeMs / 1000:
10        call_fn()
11        time.sleep(t / 1000)
12    return results
13

Complexity note: The time complexity is linear because we are calling the function a fixed number of times based on the interval and cancellation time.

  • 1Understanding how setTimeout and setInterval work is crucial for timing functions.
  • 2Recognizing the importance of managing intervals and cancellations in asynchronous programming.

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