Complex Number Multiplication
MedPrompt
A complex number can be represented as a string on the form "real+imaginaryi" where:
realis the real part and is an integer in the range[-100, 100].imaginaryis the imaginary part and is an integer in the range[-100, 100].i2 == -1.
Given two complex numbers num1 and num2 as strings, return a string of the complex number that represents their multiplications.
Example 1:
Input: num1 = "1+1i", num2 = "1+1i"
Output: "0+2i"
Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.Example 2:
Input: num1 = "1+-1i", num2 = "1+-1i"
Output: "0+-2i"
Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.
Constraints:
num1andnum2are valid complex numbers.
Approaches
3 approaches with complexity analysis and trade-offs.
This approach uses regular expressions to parse the real and imaginary parts from the input strings. A regex pattern is defined to match the complex number format, and a matcher is used to extract the numeric values.
Algorithm
-
- Define a regex pattern
(-?\d+)\+(-?\d+)ito capture the real and imaginary parts.
- Define a regex pattern
-
- For
num1, create aMatcherand extract the two captured groups.
- For
-
- Convert the captured string groups to integers
aandb.
- Convert the captured string groups to integers
-
- Repeat steps 2 and 3 for
num2to get integerscandd.
- Repeat steps 2 and 3 for
-
- Calculate the real part of the product:
real = a * c - b * d.
- Calculate the real part of the product:
-
- Calculate the imaginary part of the product:
imag = a * d + b * c.
- Calculate the imaginary part of the product:
-
- Construct the result string by concatenating the calculated real part,
+, the imaginary part, andi.
- Construct the result string by concatenating the calculated real part,
Walkthrough
The core idea is to leverage Java's java.util.regex package to robustly parse the input strings. The formula for multiplying two complex numbers (a + bi) and (c + di) is (ac - bd) + (ad + bc)i.
First, we define a regular expression pattern like (-?\d+)\+(-?\d+)i that captures two integer groups: the real part and the imaginary part. We compile this pattern and create a Matcher for each input string (num1 and num2). By calling matcher.find(), we can access the captured groups using matcher.group(1) for the real part and matcher.group(2) for the imaginary part. These captured strings are then parsed into integers (e.g., a, b, c, d). After obtaining the integer values, we apply the multiplication formula to compute the new real and imaginary parts. Finally, the resulting numbers are formatted back into the required string format "real+imaginaryi".
import java.util.regex.Matcher;import java.util.regex.Pattern; class Solution { public String complexNumberMultiply(String num1, String num2) { Pattern pattern = Pattern.compile("(-?\\d+)\\+(-?\\d+)i"); Matcher m1 = pattern.matcher(num1); m1.find(); int a = Integer.parseInt(m1.group(1)); int b = Integer.parseInt(m1.group(2)); Matcher m2 = pattern.matcher(num2); m2.find(); int c = Integer.parseInt(m2.group(1)); int d = Integer.parseInt(m2.group(2)); int realPart = a * c - b * d; int imagPart = a * d + b * c; return realPart + "+" + imagPart + "i"; }}Complexity
Time
O(1) - The length of the input strings is bounded by a small constant. The time taken by the regex engine, parsing, and arithmetic operations is therefore constant.
Space
O(1) - The space used for the pattern, matchers, and storing the parsed integers is constant regardless of the input values (within the given constraints).
Trade-offs
Pros
Very robust for parsing complex string formats.
The code can be quite readable if the regex pattern is understood.
Cons
Can be less performant than direct string manipulation due to the overhead of compiling the pattern and the regex engine's state machine.
Might be overkill for a simple and fixed format like this.
This approach parses the complex number strings by splitting them based on the + and i characters. It's simpler than using regular expressions and relies on standard string manipulation methods.
Algorithm
-
- For
num1, split the string at the'+'character to get an array of two parts.
- For
-
- Parse the first part as the real number
a.
- Parse the first part as the real number
-
- For the second part, remove the trailing
'i'and parse it as the imaginary numberb.
- For the second part, remove the trailing
-
- Repeat steps 1-3 for
num2to getcandd.
- Repeat steps 1-3 for
-
- Calculate the new real part:
real = a * c - b * d.
- Calculate the new real part:
-
- Calculate the new imaginary part:
imag = a * d + b * c.
- Calculate the new imaginary part:
-
- Concatenate the parts to form the result string:
real + "+" + imag + "i".
- Concatenate the parts to form the result string:
Walkthrough
This method avoids the complexity of regular expressions by using the String.split() and String.substring() methods. The multiplication formula (a + bi) * (c + di) = (ac - bd) + (ad + bc)i remains the same.
To parse a complex number string like "1+-1i", we can first split it by the '+' delimiter. This gives an array of two strings, for example, ["1", "-1i"]. The first element of the array is the real part, which can be directly parsed to an integer. The second element is the imaginary part with an i at the end. We remove the trailing i using substring and then parse the result to an integer. This process is repeated for both num1 and num2 to get the integer components a, b, c, d. The product is calculated using the formula, and the result is formatted into the final string.
class Solution { public String complexNumberMultiply(String num1, String num2) { String[] parts1 = num1.split("\\+"); int a = Integer.parseInt(parts1[0]); int b = Integer.parseInt(parts1[1].substring(0, parts1[1].length() - 1)); String[] parts2 = num2.split("\\+"); int c = Integer.parseInt(parts2[0]); int d = Integer.parseInt(parts2[1].substring(0, parts2[1].length() - 1)); int realPart = a * c - b * d; int imagPart = a * d + b * c; return realPart + "+" + imagPart + "i"; }}Complexity
Time
O(1) - Similar to the regex approach, the work done is constant because the input string length is constrained. `split` and `parseInt` operate on very short strings.
Space
O(1) - The space for the temporary array created by `split` is constant (size 2). The overall space usage is constant.
Trade-offs
Pros
Generally faster than the regex approach for simple delimiters.
The logic is straightforward and easy to follow.
Cons
Creates an intermediate array for the split parts, which uses slightly more memory.
Requires an extra step (
substring) to clean up the imaginary part.
This is the most efficient approach, involving direct string manipulation. It manually finds the position of the + delimiter to separate the real and imaginary parts, avoiding the overhead of regex or intermediate data structures like arrays.
Algorithm
-
- For each input string (
num1andnum2):
- a. Find the index of the
'+'character. - b. Extract the substring before
'+'and parse it as the real part. - c. Extract the substring between
'+'and the final'i'and parse it as the imaginary part.
- For each input string (
-
- Let the parsed values be
a, bfromnum1andc, dfromnum2.
- Let the parsed values be
-
- Calculate the product's real part:
real = a * c - b * d.
- Calculate the product's real part:
-
- Calculate the product's imaginary part:
imag = a * d + b * c.
- Calculate the product's imaginary part:
-
- Format the result by concatenating the values:
real + "+" + imag + "i".
- Format the result by concatenating the values:
Walkthrough
This approach offers the best performance by using low-level string operations to parse the numbers. The multiplication logic (a + bi) * (c + di) = (ac - bd) + (ad + bc)i is the foundation.
To parse a string like "1+1i", we first locate the index of the '+' character using indexOf('+'). The substring from the beginning of the string up to this index gives the real part. We use Integer.parseInt() to convert it to an integer. The substring from right after the '+' to the second-to-last character (to exclude the trailing 'i') gives the imaginary part. This is also parsed into an integer. This parsing logic is encapsulated in a helper function or applied directly to both num1 and num2 to get a, b, c, d. Once the numbers are extracted, we compute the product and format the result string.
class Solution { public String complexNumberMultiply(String num1, String num2) { int[] val1 = parseComplex(num1); int[] val2 = parseComplex(num2); int a = val1[0]; int b = val1[1]; int c = val2[0]; int d = val2[1]; int realPart = a * c - b * d; int imagPart = a * d + b * c; return realPart + "+" + imagPart + "i"; } private int[] parseComplex(String s) { int plusIndex = s.indexOf('+'); int real = Integer.parseInt(s.substring(0, plusIndex)); int imag = Integer.parseInt(s.substring(plusIndex + 1, s.length() - 1)); return new int[]{real, imag}; }}Complexity
Time
O(1) - The operations (`indexOf`, `substring`, `parseInt`) are performed on strings of a small, constant maximum length, making the overall time complexity constant.
Space
O(1) - Space is used only for storing the parsed integers and the final result string. The `substring` method may create new, short-lived string objects, but the overall space is constant.
Trade-offs
Pros
Highest performance due to direct string manipulation and no overhead from regex or intermediate collections.
Minimal memory usage.
Cons
The code might be slightly more verbose than the
splitapproach if not encapsulated in a helper function.
Solutions
Solution
class Solution { public String complexNumberMultiply ( String num1 , String num2 ) { String [] c1 = num1 . split ( "\\+|i" ); String [] c2 = num2 . split ( "\\+|i" ); int a = Integer . parseInt ( c1 [ 0 ]); int b = Integer . parseInt ( c1 [ 1 ]); int c = Integer . parseInt ( c2 [ 0 ]); int d = Integer . parseInt ( c2 [ 1 ]); return String . format ( "%d+%di" , a * c - b * d , a * d + c * b ); } }class Solution { public: string complexNumberMultiply ( string num1 , string num2 ) { int a , b , c , d ; sscanf ( num1 . c_str (), "%d+%di" , & a , & b ); sscanf ( num2 . c_str (), "%d+%di" , & c , & d ); return string ( to_string ( a * c - b * d ) + "+" + to_string ( a * d + c * b ) + "i" ); } };class Solution : def complexNumberMultiply ( self , num1 : str , num2 : str ) -> str : a , b = map ( int , num1 [: - 1 ]. split ( '+' )) c , d = map ( int , num2 [: - 1 ]. split ( '+' )) return f ' { a * c - b * d } + { a * d + c * b } i'Video walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.