LeetCode 2637: Promise Time Limit Solution

Master LeetCode problem 2637 (Promise Time Limit), a medium 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.

2637. Promise Time Limit

Medium

Problem Explanation

Explanation:

The problem requires implementing a function that wraps an asynchronous function and enforces a time limit on its execution. If the wrapped function completes within the time limit, it should resolve with the result; otherwise, it should reject with a specific message.

To solve this problem, we can utilize the Promise.race method in JavaScript. We create two promises: one for the original asynchronous function and another for a timeout that rejects if the time limit is exceeded. We then race these two promises, and the result of the race will determine whether we resolve with the original function's result or reject with the time limit exceeded message.

  • Time Complexity: The time complexity of this solution is O(1) as it does not depend on the size of the inputs.
  • Space Complexity: The space complexity is also O(1) as we only create a few additional promises and variables.

:

Solution Code

import java.util.concurrent.*;

public class Solution {
    public CompletableFuture<Object> timeLimit(Function<Object[], CompletableFuture<Object>> fn, Object[] inputs, int t) {
        CompletableFuture<Object> original = fn.apply(inputs);
        
        CompletableFuture<Object> timeout = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(t);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            return "Time Limit Exceeded";
        });
        
        return CompletableFuture.anyOf(original, timeout)
                .thenApply(result -> {
                    if (result.equals("Time Limit Exceeded")) {
                        return result;
                    } else {
                        return original.join();
                    }
                });
    }
}

Try It Yourself

Loading code editor...

Frequently Asked Questions

How to solve LeetCode 2637 (Promise Time Limit)?

This page provides optimized solutions for LeetCode problem 2637 (Promise Time Limit) 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 2637 (Promise Time Limit)?

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

Can I run code for LeetCode 2637 on DevExCode?

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

Back to LeetCode Solutions