Skip to content
Problem 537 · LeetCode 537(opens in a new tab)

Complex Number Multiplication

MediumMath

A complex number is written as a string "a+bi", where a is the real part, b is the imaginary part, both are integers, and i is the number whose square is −1. A negative part keeps its minus sign, so 2 − 7i is written "2+-7i".

You are given two such strings, num1 and num2. Return their product as a string in the same "a+bi" form.

Example 1

Input:  num1 = "3+-2i", num2 = "4+5i"
Output: "22+7i"
Why:    12 + 15i − 8i − 10i² = 22 + 7i
2 more examples and the constraints

Example 2

Input:  num1 = "0+3i", num2 = "0+3i"
Output: "-9+0i"
Why:    3i · 3i = 9i² = −9

Example 3

Input:  num1 = "2+1i", num2 = "2+-1i"
Output: "5+0i"
Why:    the imaginary terms 2·(−1) and 1·2 cancel

Constraints

  • Both strings are valid complex numbers in the form "a+bi"
  • −100 ≤ real part, imaginary part ≤ 100

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Split and expand all four termsO(1)
  2. Parse once, use the formulaO(1)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work per callVerdict
Split and expand all four termsO(1)
Passes; more code than needed
Parse once, use the formulaO(1)
Best; short and hard to get wrong

Both are constant time because each string is at most 9 characters long.

Edge cases to test

  • Negative imaginary part. "1+-1i" squared is "0+-2i": print the + and then the negative number.
  • Zero parts. A zero still prints, as in "-9+0i" or "0+0i".
  • Pure imaginary times pure imaginary. "0+3i" times "0+3i" lands on the real axis: "-9+0i".
  • Largest values. "-100+-100i" squared is "0+20000i"; products stay far inside int range.

Common mistakes

  • Adding b·d to the real part instead of subtracting it: forgetting that i² = −1.
  • Splitting on - as well, which breaks the number apart from its own minus sign.
  • Printing a negative imaginary part as a-bi instead of the required a+-bi.

How to talk through it

  1. 1Clarify. Is the format always a+bi, with +- for a negative imaginary part? Should zeros still be printed?
  2. 2Do the algebra first. (a + bi)(c + di) = ac + adi + bci + bdi², and i² = −1.
  3. 3Name the formula. Real part ac − bd, imaginary part ad + bc.
  4. 4Code the parse. Split at the single +, drop the trailing i, convert both halves to integers.
  5. 5Test out loud. Run a negative imaginary part, a zero part and the largest values.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?