Taro Logo

Add Two Integers

Easy
Jane Street logo
Jane Street
5 views
Given two integers num1 and num2, return the sum of the two integers.

Example 1:

Input: num1 = 12, num2 = 5
Output: 17
Explanation: num1 is 12, num2 is 5, and their sum is 12 + 5 = 17, so 17 is returned.

Example 2:

Input: num1 = -10, num2 = 4
Output: -6
Explanation: num1 + num2 = -6, so -6 is returned.

Constraints:

  • -100 <= num1, num2 <= 100

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 is the expected range for the integer inputs num1 and num2? Should I be concerned about integer overflow?
  2. Can num1 or num2 be negative numbers?
  3. Are num1 and num2 always valid integers, or do I need to handle potential invalid inputs like null or strings?
  4. Is there a specified return type? Should I return the sum as an integer, or is another format expected?
  5. Should I consider any specific error handling or edge cases (e.g., very large negative numbers) beyond standard integer addition?

Brute Force Solution

Approach

The goal is to find the sum of two numbers. A brute-force method to find the answer involves trying different values within a specific range until the sum is found or a defined limit is reached.

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

  1. Start with the first number.
  2. The second number is already given.
  3. Simply add these two numbers together to compute the result.
  4. Return the computed result.

Code Implementation

def add_two_integers(first_integer, second_integer):
    # This function calculates the sum of two given integers.

    # The second integer is already known from the input

    sum_of_integers = first_integer + second_integer

    # Return the sum of the two integers.
    return sum_of_integers

Big(O) Analysis

Time Complexity
O(1)The provided solution performs a single addition operation. The time taken for addition is independent of the size of the input numbers. Therefore, the time complexity is constant, represented as O(1).
Space Complexity
O(1)The provided solution simply adds two numbers. It uses a constant amount of extra memory because it does not create any auxiliary data structures that scale with the input size. It only stores the result of the addition in a variable, regardless of the magnitude of the input numbers. Therefore, the space complexity is O(1), indicating constant space usage.

Optimal Solution

Approach

We need to add two numbers together, similar to how you would do it on paper. We work digit by digit, keeping track of any carry-over to the next digit.

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

  1. Start by adding the rightmost digits of the two numbers.
  2. If the sum of those digits is 10 or more, write down the ones digit of the sum and carry the 1 over to the next column.
  3. Move to the next digits to the left in both numbers, and add those digits together, plus any carry-over from the previous step.
  4. Again, if the sum is 10 or more, write down the ones digit and carry the 1 over.
  5. Continue this process until you've added all the digits in both numbers. If there's a carry-over left at the very end, write down that carry-over as the leftmost digit of the result.
  6. The digits you've written down from right to left form the sum of the two numbers.

Code Implementation

def add_two_integers(number1, number2):
    number1_string = str(number1)
    number2_string = str(number2)
    
    max_length = max(len(number1_string), len(number2_string))
    
    number1_string = number1_string.zfill(max_length)
    number2_string = number2_string.zfill(max_length)
    
    result = ""
    carry = 0

    for i in range(max_length - 1, -1, -1):
        digit1 = int(number1_string[i])
        digit2 = int(number2_string[i])
        
        digit_sum = digit1 + digit2 + carry

        # Determine the digit to append to the result and update carry
        if digit_sum >= 10:
            result = str(digit_sum % 10) + result
            carry = 1

        else:
            result = str(digit_sum) + result
            carry = 0

    # If there's a carry left after adding all digits, add it to result
    if carry:
        result = str(carry) + result

    return int(result)

Big(O) Analysis

Time Complexity
O(n)The algorithm iterates through the digits of the two input numbers once, performing addition and carry operations. The number of iterations is determined by the length of the longer number, which we can represent as n. Each digit addition and carry operation takes constant time. Therefore, the time complexity is directly proportional to the number of digits, resulting in O(n) time complexity.
Space Complexity
O(N)The algorithm accumulates digits to form the sum. In the worst-case scenario, where the two numbers have N digits combined, the resulting sum can have up to N+1 digits. This implies the algorithm needs to store at most N+1 digits as it builds the result digit by digit. Therefore, the auxiliary space used grows linearly with the number of digits in the input numbers, resulting in O(N) space complexity where N represents the maximum number of digits in either input number.

Edge Cases

CaseHow to Handle
Integer overflow when summing large positive numbersUse a larger data type (e.g., long) or perform overflow checking before returning the result.
Integer underflow when summing large negative numbersUse a larger data type (e.g., long) or perform underflow checking before returning the result.
One or both inputs are zeroThe addition operation should handle zeros correctly without any special logic.
One input is the maximum integer value and the other is a positive number.Check for overflow by comparing the sum to the maximum integer value.
One input is the minimum integer value and the other is a negative number.Check for underflow by comparing the sum to the minimum integer value.
Both inputs are maximum and minimum integer values respectively.Check for overflow/underflow by comparing the sum to the allowed range.
Extremely large numbers represented as strings, outside of integer limits.Convert the strings to BigInteger or use a language-specific large number library to perform the addition.
One of the inputs is not an integer (e.g., float, string).Perform input validation and raise an error or convert the input to an integer before performing the addition.