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.
- Split and expand all four termsO(1)
- Parse once, use the formulaO(1)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work per call | Verdict |
|---|---|---|---|
| Split and expand all four terms | O(1) | Passes; more code than needed | |
| Parse once, use the formula | O(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-biinstead of the requireda+-bi.
How to talk through it
- 1Clarify. Is the format always
a+bi, with+-for a negative imaginary part? Should zeros still be printed? - 2Do the algebra first. (a + bi)(c + di) = ac + adi + bci + bdi², and i² = −1.
- 3Name the formula. Real part ac − bd, imaginary part ad + bc.
- 4Code the parse. Split at the single
+, drop the trailingi, convert both halves to integers. - 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?