Taro Logo

Add Two Promises

Easy
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+1
More companies
Profile picture
21 views
Given two promises promise1 and promise2, return a new promise. promise1 and promise2 will both resolve with a number. The returned promise should resolve with the sum of the two numbers.

Example 1:

Input: 
promise1 = new Promise(resolve => setTimeout(() => resolve(2), 20)), 
promise2 = new Promise(resolve => setTimeout(() => resolve(5), 60))
Output: 7
Explanation: The two input promises resolve with the values of 2 and 5 respectively. The returned promise should resolve with a value of 2 + 5 = 7. The time the returned promise resolves is not judged for this problem.

Example 2:

Input: 
promise1 = new Promise(resolve => setTimeout(() => resolve(10), 50)), 
promise2 = new Promise(resolve => setTimeout(() => resolve(-12), 30))
Output: -2
Explanation: The two input promises resolve with the values of 10 and -12 respectively. The returned promise should resolve with a value of 10 + -12 = -2.

Constraints:

  • promise1 and promise2 are promises that resolve with a number

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What will be the data type of the values resolved by the Promises? Are they guaranteed to be numbers?
  2. Could either of the Promises potentially reject, and if so, what should be the behavior of the `addTwoPromises` function?
  3. Can I assume that both Promises will eventually resolve or reject, or is there a possibility of them never resolving?
  4. Is there any specific return type expected for the sum? For example, should it be a number or a Promise?
  5. Are there any limits on the numerical values that the Promises might resolve to (e.g., are they integers, floating-point numbers, and what is the expected range)?

Brute Force Solution

Approach

We're trying to add the results of two things that will eventually give us numbers. To do it the simplest way, we wait for both of them to finish and then simply add the numbers they give us together.

Here's how the algorithm would work step-by-step:

  1. Wait for the first thing to finish and give us its number.
  2. Wait for the second thing to finish and give us its number.
  3. Once we have both numbers, add them together.
  4. Give that combined number as the final answer.

Code Implementation

import asyncio

async def add_two_promises(promise1, promise2):
    # We need to wait for the first promise to resolve to a number
    first_promise_value = await promise1

    # Then, we need to wait for the second promise
    second_promise_value = await promise2

    # Finally, we can safely add the values together.
    sum_of_promises = first_promise_value + second_promise_value

    return sum_of_promises

Big(O) Analysis

Time Complexity
O(1)The solution waits for two promises to resolve. Regardless of the complexity of the operations *within* those promises (which are not accounted for here), the `addTwoPromises` function itself performs a fixed number of operations: awaiting two promises and then performing a single addition. These steps take a constant amount of time, independent of any input size. Therefore, the time complexity is O(1).
Space Complexity
O(1)The provided plain English explanation describes waiting for two promises to resolve and then adding their results. This process requires storing the resolved values of the two promises which are numerical results. Regardless of how long the promises take to resolve, we only need space for these two numerical values. Therefore, the auxiliary space used is constant and does not depend on the size of any input N.

Optimal Solution

Approach

We need to add the results of two asynchronous operations that complete at different times. The key is to wait for both operations to finish before calculating and returning their sum. We achieve this by leveraging the promise mechanism to handle the asynchronous nature of the operations and return the result as a promise.

Here's how the algorithm would work step-by-step:

  1. Receive two promises as input.
  2. Wait for both of those promises to successfully complete.
  3. Once both promises are complete, get their resulting values.
  4. Add the two values together.
  5. Return a new promise that resolves with the sum of the two values.

Code Implementation

import asyncio

async def add_two_promises(promise_one, promise_two):
    # Ensure both promises complete before proceeding.
    result_one = await promise_one

    result_two = await promise_two

    # Calculate the sum of the resolved values.
    sum_of_results = result_one + result_two

    # Return a new promise that resolves to the sum.
    return sum_of_results

Big(O) Analysis

Time Complexity
O(1)The code waits for two promises to resolve. Regardless of how long each promise takes to resolve, the number of promises we're waiting for is fixed at two. The addition operation also takes constant time. Thus, the overall time complexity is constant, or O(1).
Space Complexity
O(1)The space complexity is O(1) because the algorithm uses a fixed number of variables to store the results of the two input promises and their sum. Regardless of how complex the asynchronous operations are or the size of any data they might internally process, the 'add two promises' function itself only requires constant extra space to hold these intermediate values. No auxiliary data structures, like arrays or hash maps that scale with the input, are created. Therefore, the auxiliary space used by this operation is constant.

Edge Cases

One or both promises reject
How to Handle:
Reject the resulting promise immediately if either of the input promises reject.
Non-numeric values returned by promises
How to Handle:
Check the types of the resolved values and reject the result if they are not numbers.
Promises that never resolve or reject (infinite pending)
How to Handle:
Implement a timeout mechanism to reject the promise if it takes too long to resolve.
Large numeric values that could lead to overflow
How to Handle:
Javascript numbers are double-precision floating point, so very large numbers will lose precision, which the solution should handle gracefully, although exact precision is not guaranteed with extremely large numbers.
Promises resolving with NaN or Infinity
How to Handle:
Explicitly check for NaN and Infinity in the resolved values and reject the promise if encountered.
Promises that resolve with negative numbers
How to Handle:
Negative number results are valid based on the problem statement, and should be handled normally through standard addition.
Promises that resolve to 0
How to Handle:
The solution works correctly with zero as it will return the sum normally.
Extremely long resolution times of promises
How to Handle:
Consider a timeout to avoid indefinite waiting; reject the promise after a reasonable duration to prevent resource exhaustion.