LeetCode 2621: Sleep Solution

Master LeetCode problem 2621 (Sleep), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2621. Sleep

Easy

Problem Explanation

Explanation

To implement the sleep function, we can use the setTimeout function in JavaScript to create a promise that resolves after the specified milliseconds. We will create a function that returns a promise that resolves after the given millis milliseconds.

  • Algorithm:

    1. Create a function sleep that takes the number of milliseconds as input.
    2. Return a new Promise that calls setTimeout with the resolve function after the specified milliseconds.
  • Time Complexity: O(1) - The function resolves after a fixed duration.

  • Space Complexity: O(1) - Constant space is used.

Solution Code

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

public class Sleep {
    public static CompletableFuture<Void> sleep(int millis) {
        CompletableFuture<Void> future = new CompletableFuture<>();
        CompletableFuture.runAsync(() -> {
            try {
                TimeUnit.MILLISECONDS.sleep(millis);
                future.complete(null);
            } catch (InterruptedException e) {
                future.completeExceptionally(e);
            }
        });
        return future;
    }

    public static void main(String[] args) {
        long t = System.currentTimeMillis();
        sleep(100).thenRun(() -> System.out.println(System.currentTimeMillis() - t)); // Example usage
    }
}

Try It Yourself

Loading code editor...

Frequently Asked Questions

How to solve LeetCode 2621 (Sleep)?

This page provides optimized solutions for LeetCode problem 2621 (Sleep) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2621 (Sleep)?

The time complexity for LeetCode 2621 (Sleep) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2621 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2621 in Java, C++, or Python.

Back to LeetCode Solutions