#2650

Design Cancellable Function

Hard
Asynchronous ProgrammingPromise HandlingGenerator Functions
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 approach efficiently manages the generator's execution and cancellation by using a promise chain and handling errors directly. This reduces unnecessary waiting and allows for immediate cancellation.

⚙️

Algorithm

6 steps
  1. 1Step 1: Create an iterator from the generator function.
  2. 2Step 2: Define a cancel function that sets an exception in the promise.
  3. 3Step 3: Use a recursive function to handle the promise resolution and generator communication.
  4. 4Step 4: If a promise resolves, send the value back to the generator.
  5. 5Step 5: If the cancel function is called, reject the promise with 'Cancelled'.
  6. 6Step 6: Handle completion and errors appropriately.
solution.py16 lines
1def cancellable(gen):
2    it = iter(gen)
3    def cancel():
4        raise 'Cancelled'
5    promise = None
6    def step(value):
7        nonlocal promise
8        try:
9            promise = next(it)
10            resolved_value = yield from promise
11            it.send(resolved_value)
12        except StopIteration as e:
13            return e.value
14        except Exception as e:
15            it.throw(e)
16    return [cancel, step]  # Adjusted for async handling

Complexity note: This complexity is due to the linear execution of promises and the generator, allowing for efficient handling of each step.

  • 1Understanding two-way communication between generators and the calling code is crucial.
  • 2Efficient error handling can significantly improve the performance and reliability of asynchronous tasks.

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