Want Help Cracking FAANG?

(Then click this)

×
Back to Question Bank

537. Complex Number Multiplication - Leetcode Solution

Code Implementation

class Solution:
    def complexNumberMultiply(self, num1: str, num2: str) -> str:
        def parse_complex(s):
            real, imag = s.split("+")
            return int(real), int(imag[:-1])

        a, b = parse_complex(num1)
        c, d = parse_complex(num2)
        real = a * c - b * d
        imag = a * d + b * c
        return f"{real}+{imag}i"
      
class Solution {
public:
    string complexNumberMultiply(string num1, string num2) {
        auto parse = [](const string& s) {
            int plus = s.find('+');
            int real = stoi(s.substr(0, plus));
            int imag = stoi(s.substr(plus + 1, s.size() - plus - 2));
            return make_pair(real, imag);
        };
        auto [a, b] = parse(num1);
        auto [c, d] = parse(num2);
        int real = a * c - b * d;
        int imag = a * d + b * c;
        return to_string(real) + "+" + to_string(imag) + "i";
    }
};
      
class Solution {
    public String complexNumberMultiply(String num1, String num2) {
        int[] n1 = parse(num1);
        int[] n2 = parse(num2);
        int real = n1[0] * n2[0] - n1[1] * n2[1];
        int imag = n1[0] * n2[1] + n1[1] * n2[0];
        return real + "+" + imag + "i";
    }
    private int[] parse(String s) {
        String[] parts = s.split("\\+");
        int real = Integer.parseInt(parts[0]);
        int imag = Integer.parseInt(parts[1].replace("i", ""));
        return new int[]{real, imag};
    }
}
      
var complexNumberMultiply = function(num1, num2) {
    function parse(s) {
        let [real, imag] = s.split("+");
        return [parseInt(real), parseInt(imag.slice(0, -1))];
    }
    const [a, b] = parse(num1);
    const [c, d] = parse(num2);
    const real = a * c - b * d;
    const imag = a * d + b * c;
    return real + "+" + imag + "i";
};
      

Problem Description

The problem asks you to multiply two complex numbers given as strings and return the result as a string in the same format. Each input string, num1 and num2, represents a complex number in the form "a+bi" where a and b are integers (they can be negative or zero). The task is to compute the product of these two complex numbers and return the answer as a string in the same "x+yi" format.

  • Both input strings are valid and always represent complex numbers in the given format.
  • There is exactly one valid solution for each input.
  • You do not need to handle invalid input or reuse elements.

Thought Process

The main challenge is to correctly parse the input strings, extract the real and imaginary parts, and then apply the rules for complex number multiplication. At first glance, one might think of converting the strings to numbers and multiplying directly, but complex numbers have their own multiplication rules:

  • For two complex numbers (a + bi) and (c + di), their product is (a*c - b*d) + (a*d + b*c)i.

The brute-force approach is to manually parse the numbers and apply the formula directly. There's no need for further optimization since the input size is small and the operations are straightforward. The key is to carefully extract the real and imaginary parts and perform the arithmetic correctly.

Solution Approach

Let's break down the solution step by step:

  1. Parse the Input Strings:
    • Each input is in the format "a+bi". We split the string at the '+' character to separate the real and imaginary parts.
    • The real part is the integer before the '+'.
    • The imaginary part is the integer after the '+', removing the trailing 'i'.
  2. Apply Complex Number Multiplication Formula:
    • Let num1 = a + bi and num2 = c + di.
    • The product is (a*c - b*d) + (a*d + b*c)i.
  3. Format the Output:
    • Combine the computed real and imaginary parts into a string in the "x+yi" format.

This approach is simple and efficient for the problem's constraints. We use basic string manipulation and arithmetic without needing extra data structures.

Example Walkthrough

Let's consider the example where num1 = "1+1i" and num2 = "1+1i":

  1. Parse Inputs:
    • num1: real = 1, imaginary = 1
    • num2: real = 1, imaginary = 1
  2. Apply Formula:
    • real part: 1 * 1 - 1 * 1 = 1 - 1 = 0
    • imaginary part: 1 * 1 + 1 * 1 = 1 + 1 = 2
  3. Format Output:
    • Result is "0+2i"

So, multiplying "1+1i" by "1+1i" yields "0+2i".

Time and Space Complexity

Brute-force Approach:

  • Parsing, arithmetic, and formatting are all O(1) operations since the input strings are of constant length.
  • Therefore, the time complexity is O(1).
  • The space complexity is also O(1) because we only use a constant amount of extra space for variables.
Optimized Approach:
  • The solution described above is already optimal for this problem.
  • No further optimization is necessary or possible given the constraints.

Summary

In summary, the problem asks for the multiplication of two complex numbers represented as strings. By parsing each string to extract the real and imaginary parts, applying the standard multiplication formula, and formatting the result, we can solve the problem efficiently. The solution is elegant because it directly leverages the mathematical properties of complex numbers, and the code is concise and easy to understand.