LeetCode 2721: Execute Asynchronous Functions in Parallel Solution
Master LeetCode problem 2721 (Execute Asynchronous Functions in Parallel), 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.
2721. Execute Asynchronous Functions in Parallel
Problem Explanation
Explanation
To solve this problem, we need to execute all the asynchronous functions in the given array in parallel and return a new promise that resolves when all the promises returned by the functions are resolved successfully or rejects if any of the promises is rejected.
We will create a new promise and iterate over the array of functions. For each function, we will execute it and store the promise in an array. We will keep track of the number of resolved promises and the first rejection if any. Once all promises are settled, we will resolve the new promise with the resolved values or reject it with the first rejection reason.
- Time complexity: O(n), where n is the number of functions in the input array.
- Space complexity: O(n) for storing promises.
Solution Code
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class Solution {
public CompletableFuture<List<Object>> promiseAll(List<Runnable> functions) {
CompletableFuture<Void>[] futures = functions.stream()
.map(func -> CompletableFuture.runAsync(func))
.toArray(CompletableFuture[]::new);
return CompletableFuture.allOf(futures)
.thenApply(ignored -> {
List<Object> results = new ArrayList<>();
for (CompletableFuture<Void> future : futures) {
results.add(future.getNow(null));
}
return results;
});
}
}Try It Yourself
Loading code editor...
Frequently Asked Questions
How to solve LeetCode 2721 (Execute Asynchronous Functions in Parallel)?
This page provides optimized solutions for LeetCode problem 2721 (Execute Asynchronous Functions in Parallel) 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 2721 (Execute Asynchronous Functions in Parallel)?
The time complexity for LeetCode 2721 (Execute Asynchronous Functions in Parallel) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2721 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2721 in Java, C++, or Python.