#2621
Sleep
EasyAsynchronous ProgrammingPromisesCallbacks
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(1) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(1)Space O(1)
The optimal solution leverages JavaScript's asynchronous capabilities using setTimeout, allowing other code to run while waiting, making it efficient and non-blocking.
⚙️
Algorithm
3 steps- 1Step 1: Create an async function named sleep that takes millis as an argument.
- 2Step 2: Return a promise that resolves after a delay using setTimeout.
- 3Step 3: Use the millis parameter to set the delay time.
solution.py5 lines
1import asyncio
2
3async def sleep(millis):
4 await asyncio.sleep(millis / 1000)
5 return Trueℹ
Complexity note: The time complexity is O(1) because the function simply sets a timer. The space complexity is also O(1) as it does not require additional space.
- 1Using asynchronous programming allows other tasks to run while waiting, improving efficiency.
- 2Understanding the difference between blocking and non-blocking code is crucial in JavaScript.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.