Domain 2MediumCORE

Complex Number Multiplication

We are given two strings representing complex numbers in the format 'a+bi'. We need to multiply them and return a string representation of the result in the same strict format ('real+imaginaryi').

Domain: Medium•Updated: 2026-08-31
#Algorithms#LeetCode#qwen3.5:9b#Math#String

537. Complex Number Multiplication

Model: qwen3.5:9b
Topics: Math,String
FAANG asked: 1
Acceptance rate: 68.4%


Problem Breakdown

We are given two strings representing complex numbers in the format “a+bi”. We need to multiply them and return a string representation of the result in the same strict format (“real+imaginaryi”).

Key Constraints & Edge Cases:

  1. Format Strictness: The output must strictly follow a+b*i. Even if the imaginary part is negative, we append it with an explicit plus sign (e.g., "0+-2i"). This means we cannot simply use a minus separator for negative coefficients; the format string logic dictates using '+' as the delimiter between real and imaginary parts.
  2. Negative Numbers: Inputs can have negative integers in a or b. We must handle parsing correctly (e.g., "1+-5i").
  3. Overflow: The range is [-100, 100]. Standard integer arithmetic will not overflow here.
  4. Parsing Logic: Since the separator between real and imaginary parts is always '+', we can safely split by this character to isolate coefficients.

Intuition

A brute-force approach would be string manipulation without mathematical logic (e.g., regex replacement), which risks errors with negative signs or varying lengths.

The core insight here is that complex number multiplication follows a fixed algebraic formula: (a+bi)(c+di)=(ac−bd)+i(ad+bc)(a + bi)(c + di) = (ac - bd) + i(ad + bc), given i2=−1i^2 = -1.

Instead of using Python’s built-in complex type directly—which might bypass the string parsing requirement—we should parse the strings to extract integers manually. This demonstrates control over data structures and algorithmic thinking. We split each input by '+', strip the trailing 'i' from the imaginary part, convert both parts to integers for calculation, apply the formula, then reconstruct the output string using a hardcoded + separator between real and imaginary components to match LeetCode’s specific formatting requirements (as seen in Example 2).

Approach

  1. Parsing: For each input string:
    • Split by '+'. The first part is the Real coefficient (aa or cc), the second part contains the Imaginary coefficient and ‘i’.
    • Strip the trailing character 'i' from the imaginary substring.
    • Convert both substrings to integers using int(). This handles negative signs automatically (e.g., "1+-5" becomes real=1, imag=-5).
  2. Calculation: Apply (ac−bd)(ac - bd) for new Real and (ad+bc)(ad + bc) for new Imaginary.
  3. Formatting: Construct the result string using an f-string with a literal '+' between the calculated integers to ensure strict adherence to output format (e.g., f"{real}+{imag}i").

Complexity Analysis

  • Time Complexity: O(N)O(N), where NN is the length of the input strings. We iterate through each string once for parsing and formatting. Since constraints limit digits significantly, this effectively behaves as constant time relative to large inputs, but technically linear in terms of character count processed.
  • Space Complexity: O(1)O(1). We use a fixed number of variables regardless of input size (excluding the space required for output string construction).

Solution

class Solution:
    def complexNumberMultiply(self, num1: str, num2: str) -> str:
        # Helper to parse "a+bi" into integers [real, imag]
        def parse_complex(s):
            real_str = s.split('+')[0]
            imag_part = s.split('+')[1].replace('i', '')
            return int(real_str), int(imag_part)

        a, b = parse_complex(num1)
        c, d = parse_complex(num2)

        # Apply formula: (a + bi)(c + di) = (ac - bd) + i(ad + bc)
        real_result = a * c - b * d
        imag_result = a * d + b * c
        
        return f"{real_result}+{imag_result}i"

Edge Cases Handled

  • Negative Imaginary Coefficients: The parser handles inputs like "1+-5i" correctly by splitting on '+' and converting the second part (which includes the minus sign) to an integer.
  • Zero Results: If multiplication results in 0 for a component,