Complex Number Multiplication

Medium · Math & Geometry · Explanation and code example

Multiply Real and Imaginary Components

How it works

Parse each input into its real and imaginary integer components. Distribute the multiplication using i² = -1: the real part is ac - bd and the imaginary part is ad + bc. Format both signed components in the required a+bi representation.

Steps

  1. Split at the separating plus and remove the trailing i.
  2. Compute real and imaginary products.
  3. Return real + "+" + imaginary + "i".

Complexity

  • Time: O(n + m) for parsing and formatting the input strings.
  • Space: O(n + m) for substring and output strings.

Things to watch for

  • The imaginary component may be negative, as in 1+-1i.
  • Keep the separating plus in the formatted result.
  • Do not use floating-point complex parsing.

Python code example

class Solution:
  def complexNumberMultiply(self, num1: str, num2: str) -> str:
    a0, a1 = self._getReala0ndImag(num1)
    b0, b1 = self._getReala0ndImag(num2)
    return str(a0 * b0 - a1 * b1) + '+' + str(a0 * b1 + a1 * b0) + 'i'

  def _getReala0ndImag(self, s: str) -> tuple:
    return int(s[:s.index('+')]), int(s[s.index('+') + 1:-1])

C++ code example

class Solution {
 public:
  string complexNumberMultiply(string num1, string num2) {
    const auto& [a0, a1] = getReala0ndImag(num1);
    const auto& [b0, b1] = getReala0ndImag(num2);
    return to_string(a0 * b0 - a1 * b1) + "+" + to_string(a0 * b1 + a1 * b0) +
           "i";
  }

 private:
  pair<int, int> getReala0ndImag(const string& s) {
    const string& real = s.substr(0, s.find_first_of('+'));
    const string& imag = s.substr(s.find_first_of('+') + 1);
    return {stoi(real), stoi(imag)};
  };
};
Source and license

Explanation by LC Tracker. Code adapted from walkccc / Peng-Yu Chen · MIT license. Node types are supplied by LeetCode where needed.

Your recall check is in progress. Write your attempt before revealing the explanation.

Resume recall check

Browse all problem explanations