#2637
Promise Time Limit
MediumPromise HandlingAsynchronous Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(1) | O(1) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(1)Space O(1)
The optimal solution leverages asynchronous programming to manage the timing and execution of the function efficiently. By using promises and timers, we can ensure that we handle the function's execution within the specified time limit without blocking the main thread.
⚙️
Algorithm
3 steps- 1Step 1: Create a wrapper function that returns a new promise.
- 2Step 2: Set a timeout that rejects the promise after t milliseconds.
- 3Step 3: Call the original function and resolve the promise with its result if it completes in time.
solution.py14 lines
1import asyncio
2
3def timeLimit(fn, t):
4 async def wrapper(*args, **kwargs):
5 loop = asyncio.get_event_loop()
6 future = loop.create_future()
7 timer = loop.call_later(t / 1000, lambda: future.set_exception(Exception('Time Limit Exceeded')))
8 try:
9 result = await fn(*args, **kwargs)
10 future.set_result(result)
11 finally:
12 timer.cancel()
13 return future
14 return wrapperℹ
Complexity note: The time complexity remains O(1) as we are still just waiting for either the function to resolve or the timeout to occur.
- 1Asynchronous programming is crucial for handling time-sensitive operations.
- 2Using promises allows for better control over function execution and error handling.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.