Facebook Pixel

537. Complex Number Multiplication

MediumMathStringSimulation
Leetcode Link

Problem Description

This problem asks you to multiply two complex numbers that are given as strings and return the result as a string in the same format.

A complex number is represented as a string in the format "real+imaginaryi" where:

  • The real part is an integer between -100 and 100
  • The imaginary part is an integer between -100 and 100
  • The letter i represents the imaginary unit where i² = -1

For example, "1+2i" represents a complex number with real part 1 and imaginary part 2.

To multiply two complex numbers (a₁ + b₁i) and (a₂ + b₂i), you use the formula: (a₁ + b₁i) × (a₂ + b₂i) = (a₁×a₂ - b₁×b₂) + (a₁×b₂ + a₂×b₁)i

The real part of the result is (a₁×a₂ - b₁×b₂) and the imaginary part is (a₁×b₂ + a₂×b₁).

Given two complex number strings num1 and num2, you need to:

  1. Parse each string to extract the real and imaginary parts
  2. Apply the multiplication formula
  3. Return the result in the same string format "real+imaginaryi"

For instance, if num1 = "1+1i" and num2 = "1+1i", the multiplication would be:

  • Real part: 1×1 - 1×1 = 0
  • Imaginary part: 1×1 + 1×1 = 2
  • Result: "0+2i"
Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

Intuition

The key insight is recognizing that this is a direct application of complex number multiplication. When we multiply two complex numbers algebraically, we treat them like binomials and use the distributive property (FOIL method).

Let's think through the multiplication (a₁ + b₁i) × (a₂ + b₂i):

  • First: a₁ × a₂ = a₁a₂
  • Outer: a₁ × b₂i = a₁b₂i
  • Inner: b₁i × a₂ = a₂b₁i
  • Last: b₁i × b₂i = b₁b₂i²

Since i² = -1, the last term becomes -b₁b₂. Combining all terms: a₁a₂ + a₁b₂i + a₂b₁i - b₁b₂ = (a₁a₂ - b₁b₂) + (a₁b₂ + a₂b₁)i

The main challenge is parsing the string format. We notice that:

  • The string always follows the pattern "real+imaginaryi"
  • The + sign separates the real and imaginary parts
  • The i at the end marks the imaginary component

To extract the numbers, we can:

  1. Remove the trailing i character
  2. Split the string by the + sign
  3. Convert the resulting parts to integers

Once we have the four values (real and imaginary parts of both numbers), we simply apply the multiplication formula and format the result back into the required string format.

The solution is straightforward because the problem guarantees a consistent input format and doesn't require handling edge cases like missing parts or different signs between components.

Learn more about Math patterns.

Solution Approach

The solution follows a simulation approach where we parse the complex numbers and apply the multiplication formula directly.

Step 1: Parse the complex numbers

For each complex number string, we need to extract the real and imaginary parts. Since the format is "real+imaginaryi", we:

  • Remove the trailing "i" character using num1[:-1] and num2[:-1]
  • Split the remaining string by the "+" sign to separate real and imaginary parts
  • Convert both parts to integers using map(int, ...)

For example, "1+2i" becomes:

  • After removing "i": "1+2"
  • After splitting by "+": ["1", "2"]
  • After converting to integers: [1, 2]

Step 2: Apply the multiplication formula

With the parsed values:

  • a1, b1 from num1 (real and imaginary parts)
  • a2, b2 from num2 (real and imaginary parts)

We calculate:

  • Real part of result: a1 * a2 - b1 * b2
  • Imaginary part of result: a1 * b2 + a2 * b1

Step 3: Format the result

Using Python's f-string, we construct the result string in the required format: f"{a1 * a2 - b1 * b2}+{a1 * b2 + a2 * b1}i"

This ensures the result follows the same "real+imaginaryi" pattern.

The entire solution is implemented in a single line after parsing, making it both concise and efficient with O(1) time and space complexity, as we only perform constant operations regardless of the input values.

Ready to land your dream job?

Unlock your dream job with a 5-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through multiplying num1 = "2+3i" and num2 = "4+-5i".

Step 1: Parse the complex numbers

For num1 = "2+3i":

  • Remove the trailing "i": "2+3"
  • Split by "+": ["2", "3"]
  • Convert to integers: a1 = 2, b1 = 3

For num2 = "4+-5i":

  • Remove the trailing "i": "4+-5"
  • Split by "+": ["4", "-5"]
  • Convert to integers: a2 = 4, b2 = -5

Step 2: Apply the multiplication formula

Using (a1 + b1i) × (a2 + b2i) = (a1×a2 - b1×b2) + (a1×b2 + a2×b1)i:

Real part calculation:

  • a1 × a2 - b1 × b2
  • 2 × 4 - 3 × (-5)
  • 8 - (-15)
  • 8 + 15 = 23

Imaginary part calculation:

  • a1 × b2 + a2 × b1
  • 2 × (-5) + 4 × 3
  • -10 + 12
  • 2

Step 3: Format the result

Combine the real part (23) and imaginary part (2) into the string format:

  • Result: "23+2i"

This matches what we'd expect from manually multiplying (2+3i)(4-5i):

  • First: 2 × 4 = 8
  • Outer: 2 × (-5i) = -10i
  • Inner: 3i × 4 = 12i
  • Last: 3i × (-5i) = -15i² = 15 (since i² = -1)
  • Combining: 8 + 15 + (-10i + 12i) = 23 + 2i

Solution Implementation

1class Solution:
2    def complexNumberMultiply(self, num1: str, num2: str) -> str:
3        """
4        Multiply two complex numbers given as strings in the format "a+bi".
5      
6        Complex number multiplication formula: (a1 + b1i) * (a2 + b2i) = (a1*a2 - b1*b2) + (a1*b2 + a2*b1)i
7      
8        Args:
9            num1: First complex number as string (e.g., "1+2i")
10            num2: Second complex number as string (e.g., "3+4i")
11      
12        Returns:
13            Product of the two complex numbers as string in format "a+bi"
14        """
15        # Parse the real and imaginary parts from the first complex number
16        # Remove the trailing 'i' and split by '+' to get both parts
17        real_part_1, imaginary_part_1 = map(int, num1[:-1].split("+"))
18      
19        # Parse the real and imaginary parts from the second complex number
20        real_part_2, imaginary_part_2 = map(int, num2[:-1].split("+"))
21      
22        # Calculate the real part of the product: a1*a2 - b1*b2
23        result_real = real_part_1 * real_part_2 - imaginary_part_1 * imaginary_part_2
24      
25        # Calculate the imaginary part of the product: a1*b2 + a2*b1
26        result_imaginary = real_part_1 * imaginary_part_2 + real_part_2 * imaginary_part_1
27      
28        # Format and return the result as "a+bi"
29        return f"{result_real}+{result_imaginary}i"
30
1class Solution {
2    /**
3     * Multiplies two complex numbers given as strings.
4     * Complex numbers are in the format "a+bi" where a and b are integers.
5     * 
6     * @param num1 First complex number as string (e.g., "1+2i")
7     * @param num2 Second complex number as string (e.g., "3+4i")
8     * @return Product of the two complex numbers as string
9     */
10    public String complexNumberMultiply(String num1, String num2) {
11        // Parse both complex numbers to extract real and imaginary parts
12        int[] firstComplex = parseComplexNumber(num1);
13        int[] secondComplex = parseComplexNumber(num2);
14      
15        // Extract real and imaginary components
16        int real1 = firstComplex[0];
17        int imaginary1 = firstComplex[1];
18        int real2 = secondComplex[0];
19        int imaginary2 = secondComplex[1];
20      
21        // Apply complex multiplication formula: (a + bi) * (c + di) = (ac - bd) + (ad + bc)i
22        int resultReal = real1 * real2 - imaginary1 * imaginary2;
23        int resultImaginary = real1 * imaginary2 + real2 * imaginary1;
24      
25        // Format and return the result as "real+imaginaryi"
26        return resultReal + "+" + resultImaginary + "i";
27    }
28
29    /**
30     * Parses a complex number string to extract real and imaginary parts.
31     * 
32     * @param complexNumber Complex number string in format "a+bi"
33     * @return Array containing [real part, imaginary part]
34     */
35    private int[] parseComplexNumber(String complexNumber) {
36        // Remove the trailing 'i' character
37        String withoutI = complexNumber.substring(0, complexNumber.length() - 1);
38      
39        // Split by '+' to separate real and imaginary parts
40        String[] parts = withoutI.split("\\+");
41      
42        // Parse and return both parts as integers
43        int realPart = Integer.parseInt(parts[0]);
44        int imaginaryPart = Integer.parseInt(parts[1]);
45      
46        return new int[] {realPart, imaginaryPart};
47    }
48}
49
1class Solution {
2public:
3    string complexNumberMultiply(string num1, string num2) {
4        // Parse the real and imaginary parts from the first complex number
5        // Format: "real+imaginaryi"
6        int real1, imaginary1;
7        sscanf(num1.c_str(), "%d+%di", &real1, &imaginary1);
8      
9        // Parse the real and imaginary parts from the second complex number
10        int real2, imaginary2;
11        sscanf(num2.c_str(), "%d+%di", &real2, &imaginary2);
12      
13        // Apply complex number multiplication formula:
14        // (a + bi) * (c + di) = (ac - bd) + (ad + bc)i
15        int resultReal = real1 * real2 - imaginary1 * imaginary2;
16        int resultImaginary = real1 * imaginary2 + real2 * imaginary1;
17      
18        // Format the result as a string in the form "real+imaginaryi"
19        return to_string(resultReal) + "+" + to_string(resultImaginary) + "i";
20    }
21};
22
1/**
2 * Multiplies two complex numbers represented as strings
3 * @param num1 - First complex number in format "a+bi"
4 * @param num2 - Second complex number in format "a+bi"
5 * @returns The product of the two complex numbers in format "a+bi"
6 */
7function complexNumberMultiply(num1: string, num2: string): string {
8    // Parse the first complex number by removing the trailing 'i' and splitting by '+'
9    // Extract real part (a1) and imaginary part (b1)
10    const [realPart1, imaginaryPart1]: number[] = num1
11        .slice(0, -1)  // Remove the trailing 'i'
12        .split('+')    // Split by '+' to separate real and imaginary parts
13        .map(Number);  // Convert string parts to numbers
14  
15    // Parse the second complex number in the same manner
16    // Extract real part (a2) and imaginary part (b2)
17    const [realPart2, imaginaryPart2]: number[] = num2
18        .slice(0, -1)  // Remove the trailing 'i'
19        .split('+')    // Split by '+' to separate real and imaginary parts
20        .map(Number);  // Convert string parts to numbers
21  
22    // Apply complex number multiplication formula:
23    // (a1 + b1i) * (a2 + b2i) = (a1*a2 - b1*b2) + (a1*b2 + a2*b1)i
24    const resultRealPart: number = realPart1 * realPart2 - imaginaryPart1 * imaginaryPart2;
25    const resultImaginaryPart: number = realPart1 * imaginaryPart2 + realPart2 * imaginaryPart1;
26  
27    // Format and return the result as a string in "a+bi" format
28    return `${resultRealPart}+${resultImaginaryPart}i`;
29}
30

Time and Space Complexity

The time complexity is O(1) because:

  • Parsing the two complex number strings using split() and map() takes constant time since the input format is fixed (each number has exactly one real part and one imaginary part)
  • The arithmetic operations (4 multiplications and 2 additions/subtractions) are all constant time operations
  • String formatting to create the output also takes constant time

The space complexity is O(1) because:

  • Only a fixed number of integer variables (a1, b1, a2, b2) are created regardless of input
  • The intermediate calculations don't require additional space that scales with input
  • The output string has a fixed format and doesn't grow with input size

Learn more about how to find time and space complexity quickly.

Common Pitfalls

1. Incorrect Parsing of Negative Numbers

The current solution assumes the format is always "a+bi" and splits by "+". However, when the imaginary part is negative, the format becomes "a-bi" (e.g., "1-2i"). Using split("+") on "1-2i" will fail to parse correctly.

Example of the issue:

  • Input: "1-2i"
  • After removing "i": "1-2"
  • split("+") returns: ["1-2"] (only one element, causing an error)

Solution: Replace the "+" split approach with a more robust parsing method that handles both positive and negative imaginary parts:

def parse_complex(num_str):
    # Remove the trailing 'i'
    num_str = num_str[:-1]
  
    # Find the position of '+' or '-' after the first character
    # This handles negative real parts correctly
    for i in range(1, len(num_str)):
        if num_str[i] in ['+', '-']:
            real = int(num_str[:i])
            imaginary = int(num_str[i:])  # Include the sign
            return real, imaginary
  
    # If no '+' or '-' found, it's a pure real or pure imaginary number
    # This shouldn't happen based on problem constraints
    return int(num_str), 0

Alternative Solution using replace:

# Convert the string to handle negative imaginary parts
# Replace "+-" with "-" to normalize the format
a1, b1 = map(int, num1[:-1].replace("+-", "-").replace("-", "+-").split("+"))
a2, b2 = map(int, num2[:-1].replace("+-", "-").replace("-", "+-").split("+"))

2. Edge Case: Pure Real or Pure Imaginary Numbers

While the problem states the format is "real+imaginaryi", some implementations might need to handle edge cases like "5+0i" or "0+3i". The current solution handles these correctly, but developers might optimize away the zero terms incorrectly.

Pitfall Example: Someone might try to "optimize" the output by removing zero terms:

# Incorrect optimization
if result_imaginary == 0:
    return str(result_real)  # Wrong! Should still be "5+0i"

Correct Approach: Always maintain the required format "real+imaginaryi" regardless of zero values.

Discover Your Strengths and Weaknesses: Take Our 5-Minute Quiz to Tailor Your Study Plan:

Which data structure is used to implement priority queue?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More