We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Sleep

Number: 2733

Difficulty: Easy

Paid? No

Companies: Google, Adobe, Apple, Bloomberg


Problem Description

Implement an asynchronous function named sleep that takes a positive integer millis and returns a promise (or equivalent in other languages) that resolves after waiting for millis milliseconds.


Key Insights

  • The challenge requires creating a delay mechanism that resolves asynchronously.
  • In JavaScript, the built-in setTimeout can be used to schedule the resolution of a promise.
  • In other languages, similar asynchronous timing functions or libraries (e.g., asyncio in Python, CompletableFuture in Java) will achieve the delay.
  • The problem does not require returning a specific value; any resolved value is acceptable once the delay is complete.

Space and Time Complexity

Time Complexity: O(1) – The delay operation itself does not depend on the input size but rather waits for a fixed time. Space Complexity: O(1) – Only a constant amount of extra space is used.


Solution

We solve this problem by returning an asynchronous delay that waits for the specified number of milliseconds before resolving. In JavaScript, we can create a new promise that internally calls setTimeout with the provided millisecond delay, and then resolves the promise. Similar concepts apply to Python using asyncio.sleep, to Java using CompletableFuture.delayedExecutor, and to C++ using std::promise with a thread that sleeps. The key trick is to leverage built-in timing functions to handle the asynchronous waiting efficiently.


Code Solutions

import asyncio

# Define the asynchronous sleep function using asyncio.sleep
async def sleep(millis: int):
    # Convert milliseconds to seconds for asyncio.sleep
    await asyncio.sleep(millis / 1000)
    # Return any value; here we simply return the input for demonstration
    return millis

# Example usage:
# async def main():
#     t = 100
#     result = await sleep(t)
#     print(f"Completed sleep of {result} milliseconds")
# asyncio.run(main())
← Back to All Questions