# Complex Number Multiplication
**Difficulty:** MEDIUM
[External](https://leetcode.com/problems/complex-number-multiplication)
Canonical: https://scaleengineer.com/dsa/problems/complex-number-multiplication
**Patterns:** [Math](https://scaleengineer.com/dsa/patterns/math)
**Data structures:** String
---
## Problem
A [complex number](https://en.wikipedia.org/wiki/Complex%5Fnumber) can be represented as a string on the form `"**real**+**imaginary**i"` where:

* `real` is the real part and is an integer in the range `[-100, 100]`.
* `imaginary` is 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:**

* `num1` and `num2` are valid complex numbers.

# Approaches
## Parsing with Regular Expressions
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.
**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).
**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.
### Explanation
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"`.

```java
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";
    }
}
```
### Algorithm
- 1. Define a regex pattern `(-?\d+)\+(-?\d+)i` to capture the real and imaginary parts.
- 2. For `num1`, create a `Matcher` and extract the two captured groups.
- 3. Convert the captured string groups to integers `a` and `b`.
- 4. Repeat steps 2 and 3 for `num2` to get integers `c` and `d`.
- 5. Calculate the real part of the product: `real = a * c - b * d`.
- 6. Calculate the imaginary part of the product: `imag = a * d + b * c`.
- 7. Construct the result string by concatenating the calculated real part, `+`, the imaginary part, and `i`.

## Parsing with String Splitting
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.
**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.
**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.
### Explanation
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.

```java
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";
    }
}
```
### Algorithm
- 1. For `num1`, split the string at the `'+'` character to get an array of two parts.
- 2. Parse the first part as the real number `a`.
- 3. For the second part, remove the trailing `'i'` and parse it as the imaginary number `b`.
- 4. Repeat steps 1-3 for `num2` to get `c` and `d`.
- 5. Calculate the new real part: `real = a * c - b * d`.
- 6. Calculate the new imaginary part: `imag = a * d + b * c`.
- 7. Concatenate the parts to form the result string: `real + "+" + imag + "i"`.

## Manual Parsing with `indexOf` and `substring`
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.
**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.
**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 `split` approach if not encapsulated in a helper function.
### Explanation
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.

```java
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};
    }
}
```
### Algorithm
- 1. For each input string (`num1` and `num2`):
  - 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.
- 2. Let the parsed values be `a, b` from `num1` and `c, d` from `num2`.
- 3. Calculate the product's real part: `real = a * c - b * d`.
- 4. Calculate the product's imaginary part: `imag = a * d + b * c`.
- 5. Format the result by concatenating the values: `real + "+" + imag + "i"`.

# Solutions
### Java

```java
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 ); } }
```

### CPP

```cpp
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" ); } };
```

### Python

```python
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'
```
