Sleep solution and explanation
9 more videos on this problem
Sleep - Leetcode 2621 - JavaScript 30-Day ChallengeNeetCodeIO · 19:13 · 13K views
#day13 |2621. Sleep | 30 Days of Javascript | Leetcode-2621 | 30 Days Challenge | setTimeout()Coding with Ankita · 12:10 · 2K views
Sleep | Leetcode 2621 | Promises and Time | 30 Days of JavaScript #leetcode #javascript #asyncawaitLearn With Chirag · 5:53 · 2K views
2621. Sleep - Leetcode JavaScript Solution with ExplanationEndeavour Monk · 8:46 · 938 views
2621 Sleep LeetCode 15 May 2023AnshulOnTech · 4:07 · 869 views
Leetcode 2621 Javascript Problems Solving | Sleep function that resolves after given milli seconds.Tech Intuitors · 2:48 · 248 views
LeetCode 30-Days JavaScript Challenge: Solving "Sleep" (2621) #leetcode #javascript #tech #codingJcb Nesh · 0:29 · 242 views
2621. Sleep - Day 11/30 Leetcode Javascript ChallengeProgramming Live with Larry · 7:09 · 223 views
Day 11 of 30: JavaScript Coding Challenge on LeetCode - Task 2621 SleepvanAmsen · 4:17 · 110 views
#Leetcode 2621 Sleep function 🚀 Day 13 👨💻 30Days of JavaScript Challenge LeetCodeRajat Talesra · 3:59 · 101 views
The problem
Given a positive integer millis, write an asynchronous function that sleeps for millis milliseconds. It can resolve any value.
Example 1:
Input: millis = 100
Output: 100
Explanation: It should return a promise that resolves after 100ms.
let t = Date.now();
sleep(100).then(() => {
console.log(Date.now() - t); // 100
});
Example 2:
Input: millis = 200 Output: 200 Explanation: It should return a promise that resolves after 200ms.
Constraints:
1 <= millis <= 1000
Approach overview
Problem Overview: Implement a sleep function that pauses execution for a specified number of milliseconds and resolves afterward. The function should return a promise-like asynchronous result so the caller can await it.
Approach 1: Promise with setTimeout (O(1) time, O(1) space)
The most common JavaScript implementation wraps setTimeout inside a Promise. When the function is called, you create a new promise and schedule setTimeout to call resolve after millis milliseconds. The event loop handles the delay while the main thread continues processing other tasks. This approach relies on the browser or Node.js timer system and is the standard way to implement delays in Promises-based code. Since the function only schedules a timer, the algorithmic complexity is constant: O(1) time and O(1) space.
Approach 2: Python asyncio.sleep (O(1) time, O(1) space)
Python’s asyncio.sleep provides the same behavior in an asynchronous programming environment. The function is defined with async and awaits asyncio.sleep(milliseconds / 1000). Instead of blocking the thread, the coroutine yields control back to the event loop until the timer expires. This allows other coroutines to run concurrently, which is the core advantage of asynchronous I/O. Like the JavaScript version, the operation schedules a timer and therefore runs in O(1) time and O(1) space.
Approach 3: Task.Delay / CompletableFuture Delay (O(1) time, O(1) space)
Languages with structured async frameworks provide built-in delay utilities. In C#, Task.Delay(milliseconds) returns a task that completes after the specified duration. In Java, a similar effect can be achieved using CompletableFuture with a delayed executor or scheduled task. Both rely on runtime schedulers rather than blocking the thread. The caller can await or chain the returned future, integrating naturally with concurrency primitives. Because the runtime simply schedules a timer, the complexity remains O(1) time and O(1) space.
Recommended for interviews: The JavaScript Promise + setTimeout implementation is the expected answer because it demonstrates understanding of the event loop and asynchronous control flow. Showing that you know built-in delay primitives like asyncio.sleep or Task.Delay also signals familiarity with async runtimes. The key insight interviewers look for is recognizing that you should schedule a timer rather than block execution.
Approach 1: Using Promises and setTimeout in JavaScript
This approach utilizes JavaScript's Promise and setTimeout to create an asynchronous sleep function. The setTimeout function is used to delay the promise resolution by the specified number of milliseconds.
function sleep(millis) {
return new Promise(resolve => setTimeout(resolve, millis));
}The sleep function creates a new Promise. Inside the promise, setTimeout is used to delay the invocation of the resolve function by millis milliseconds. This means the promise will be resolved after the specified delay, implementing a "sleep" behavior.
Time Complexity: O(1) because the delay is constant independent of any input size.
Space Complexity: O(1) as we're only storing the promise which requires constant space.
Approach 2: Using Task.Delay in C#
This approach uses C#'s Task.Delay method to implement the asynchronous sleep function. Task.Delay returns a task that completes after the specified delay.
using System.Threading.Tasks;
public class Solution {
public async Task Sleep(int millis) {
await Task.Delay(millis);
}
}In C#, the Sleep method is marked async to indicate it can execute asynchronously. We use Task.Delay, which returns a Task that completes after a delay specified by millis. The await keyword is used to asynchronously wait for the task's completion.
Time Complexity: O(1). The execution time is constant due to the non-blocking nature of tasks.
Space Complexity: O(1) as we're dealing with a single task object.
Approach 3: Using Java's CompletableFuture
This method involves Java's CompletableFuture class which allows for asynchronous programming. We can use this to simulate a sleep by combining it with Thread.sleep.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class Solution {
public static CompletableFuture<Void> sleep(int millis) {
return CompletableFuture.runAsync(() -> {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
}The sleep function uses CompletableFuture.runAsync to execute a task asynchronously that sleeps for the given milliseconds using Thread.sleep. CompletableFuture handles asynchronous computations and allows us to define a function to be run asynchronously.
Time Complexity: O(1). The delay action is constant time as it directly calls Thread.sleep.
Space Complexity: O(1) since the CompletableFuture only maintains a completion stage.
Approach 4: Python's asyncio.sleep
In Python, the asyncio library provides an asynchronous infrastructure, with asyncio.sleep providing sleep functionality without blocking.
import asyncio
async def sleep(millis):
await asyncio.sleep(millis / 1000)The sleep function is asynchronous, using asyncio.sleep to suspend the coroutine for the specified duration. The function converts milliseconds to seconds (since asyncio.sleep accepts seconds) and then awaits the sleep.
Time Complexity: O(1). The delay is managed internally by the event loop, thus constant.
Space Complexity: O(1) as only the coroutine object is being utilized.
Approach 5: Default Approach
async function sleep(millis: number): Promise<void> {
return new Promise(r => setTimeout(r, millis));
}
/**
* let t = Date.now()
* sleep(100).then(() => console.log(Date.now() - t)) // 100
*/Complexity comparison
| Approach | Complexity |
|---|---|
| Using Promises and setTimeout in JavaScript | Time Complexity: O(1) because the delay is constant independent of any input size. |
| Using Task.Delay in C# | Time Complexity: O(1). The execution time is constant due to the non-blocking nature of tasks. |
| Using Java's CompletableFuture | Time Complexity: O(1). The delay action is constant time as it directly calls |
| Python's asyncio.sleep | Time Complexity: O(1). The delay is managed internally by the event loop, thus constant. |
| Default Approach | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Promise with setTimeout (JavaScript) | O(1) | O(1) | Standard solution in JavaScript environments using promises and the event loop |
| asyncio.sleep (Python) | O(1) | O(1) | Async Python programs using asyncio coroutines |
| Task.Delay / CompletableFuture Delay | O(1) | O(1) | C# or Java async workflows that rely on task or future scheduling |
Frequently asked questions
Is Sleep easy or hard?
Sleep is classified as an Easy problem. The challenge is recognizing the correct async primitive—such as Promise with setTimeout—rather than implementing any complex algorithm or data structure.
Sleep Python/Java solution
In Python, define an async function and call await asyncio.sleep(milliseconds / 1000). In Java, use CompletableFuture with a delayed executor or scheduled task to resolve after the delay. Both rely on non-blocking asynchronous scheduling.
How to solve Sleep in O(1)?
Create a promise that resolves after a timer fires. In JavaScript, call setTimeout inside a Promise and resolve it after the given milliseconds. Since the code only schedules a timer without loops or additional data structures, the complexity stays O(1).
What is the best approach for Sleep?
The standard approach uses a Promise wrapped around setTimeout. The function returns new Promise(resolve => setTimeout(resolve, millis)), which schedules a timer and resolves after the delay. This integrates cleanly with async/await and runs in O(1) time and O(1) space.
Is Sleep asked at Google/Amazon/Meta?
Sleep-style problems appear in JavaScript or async programming interviews, especially for frontend or full-stack roles. Companies like Amazon and Meta often test understanding of promises, event loops, and asynchronous execution patterns.
What data structure is used in Sleep?
No specialized data structure is required. The solution relies on asynchronous runtime primitives such as timers, promises, tasks, or futures that are managed internally by the language runtime or event loop.
What is the time complexity of Sleep?
The algorithmic complexity is O(1) time and O(1) space because the function only schedules a timer. The runtime environment handles the delay through the event loop or scheduler rather than executing additional computation.
