#2723

Add Two Promises

Easy
Promise HandlingAsynchronous Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach also uses Promise.all but emphasizes the efficiency of handling promises without unnecessary waiting or chaining, ensuring we get the sum directly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use Promise.all to handle both promises concurrently.
  2. 2Step 2: Once resolved, destructure the results to get the values directly.
  3. 3Step 3: Return the sum of the values immediately.
solution.py2 lines
1def add_two_promises(promise1, promise2):
2    return Promise.all([promise1, promise2]).then(lambda a, b: a + b)

Complexity note: The time complexity remains O(n) as we still wait for both promises. The space complexity is O(1) since we are not storing additional data.

  • 1Understanding how promises work is crucial for handling asynchronous operations.
  • 2Using Promise.all allows for concurrent resolution of multiple promises.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.