We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Complex Number Multiplication

Number: 537

Difficulty: Medium

Paid? No

Companies: Amazon


Problem Description

Given two strings representing complex numbers in the form "a+bi" where a and b are integers, compute their product and return the result as a string in the same format.


Key Insights

  • Parse each complex number string to separate the real and imaginary parts.
  • Use the formula for complex multiplication: (a+bi) * (c+di) = (ac - bd) + (ad + bc)i.
  • Return the result formatted as "real+imaginaryi", ensuring the sign for the imaginary part is included.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the input strings (parsing). Space Complexity: O(1), since only a fixed number of variables are used.


Solution

The solution involves parsing the input strings to extract the integer values for the real and imaginary parts. We then apply the multiplication formula directly. Special care is taken when parsing the input string because the imaginary part might include a negative sign. After computing the real part as (ac - bd) and the imaginary part as (ad + bc), we format and return the final result string.


Code Solutions

# Function to multiply two complex numbers represented as strings
def complexNumberMultiply(num1: str, num2: str) -> str:
    # Helper function to parse a complex number string into real and imaginary parts
    def parse_complex(s: str):
        # Remove the trailing 'i'
        s = s[:-1]
        # Find the '+' sign that separates the real and imaginary parts (starting from index 1 to ignore any leading negative for the real part)
        plus_index = s.find('+', 1)
        # Parse the real part and the imaginary part from the string
        real_part = int(s[:plus_index])
        imaginary_part = int(s[plus_index + 1:])
        return real_part, imaginary_part

    # Parse both complex number strings
    a, b = parse_complex(num1)
    c, d = parse_complex(num2)
    
    # Compute the product using the formula: (a+bi)*(c+di) = (ac - bd) + (ad + bc)i
    real_result = a * c - b * d
    imaginary_result = a * d + b * c
    
    # Return the result in the required format
    return str(real_result) + "+" + str(imaginary_result) + "i"

# Example usage:
print(complexNumberMultiply("1+1i", "1+1i"))  # Output should be "0+2i"
← Back to All Questions