LeetCode 537: Complex Number Multiplication Solution in Python – A Step-by-Step Guide

Imagine you’re handed two complex numbers—like "1+2i" and "3+4i"—and your task is to multiply them, juggling their real and imaginary parts to get a result like "5+10i," all while working with strings instead of numbers. That’s the neat challenge of LeetCode 537: Complex Number Multiplication, an easy-to-medium problem that’s a fantastic way to practice string parsing and arithmetic in Python. We’ll explore two solutions: the Best Solution, a direct parsing and multiplication approach that’s efficient and clear, and an Alternative Solution, a split and recombine method that’s straightforward but slightly more verbose. With detailed examples, clear code, and a friendly tone—especially for the parsing trick—this guide will help you conquer complex multiplication, whether you’re new to coding or brushing up. Let’s dive into the numbers and start multiplying!

What Is LeetCode 537: Complex Number Multiplication?

Section link icon

In LeetCode 537: Complex Number Multiplication, you’re given two strings num1 and num2 representing complex numbers in the format "a+bi" (e.g., "1+2i"), where a is the real part and b is the imaginary part (with i as the imaginary unit). Your task is to multiply them and return the result as a string in the same format. For example, multiplying "1+1i" and "1+1i" yields "0+2i" because (1 + i)(1 + i) = 1 + 2i + i² = 1 + 2i - 1 = 0 + 2i. This problem tests string manipulation and basic math, related to LeetCode 43: Multiply Strings for string-based arithmetic.

Problem Statement

  • Input:
    • num1 (str): First complex number (e.g., "a+bi").
    • num2 (str): Second complex number (e.g., "c+di").
  • Output: String—product in "a+bi" format.
  • Rules: Parse strings, multiply using (a + bi)(c + di) = (ac - bd) + (ad + bc)i, return as string.

Constraints

  • num1 and num2 are valid complex numbers in "a+bi" format.
  • a, b, c, d are integers in range [-100, 100].
  • Input strings length ≤ 12.

Examples

  • Input: num1 = "1+1i", num2 = "1+1i"
    • Output: "0+2i"
    • (1 + i)(1 + i) = 1 + 2i - 1 = 0 + 2i.
  • Input: num1 = "1+-2i", num2 = "1+-2i"
    • Output: "-3+-4i"
    • (1 - 2i)(1 - 2i) = 1 - 4i + 4 = -3 - 4i.
  • Input: num1 = "0+0i", num2 = "5+5i"
    • Output: "0+0i"
    • (0 + 0i)(5 + 5i) = 0.

Understanding the Problem: Multiplying Complex Numbers

Section link icon

To solve LeetCode 537: Complex Number Multiplication in Python, we need to parse two strings into their real and imaginary parts, multiply them using the formula (a + bi)(c + di) = (ac - bd) + (ad + bc)i, and format the result as a string. A naive approach might involve complex regex or manual character-by-character parsing, but with the consistent "a+bi" format, we can simplify. We’ll explore:

  • Best Solution (Direct Parsing and Multiplication): O(1) time, O(1) space—fast and concise.
  • Alternative Solution (Split and Recombine): O(1) time, O(1) space—clear but more steps.

Let’s dive into the direct parsing solution with a friendly breakdown!

Best Solution: Direct Parsing and Multiplication

Section link icon

Why Direct Parsing Wins

The direct parsing and multiplication solution is the best for LeetCode 537 because it efficiently extracts real and imaginary parts using string splitting and basic operations, performs the multiplication in one step, and formats the result, all in O(1) time (since string lengths are bounded) and O(1) space. It’s like cracking open the strings and doing the math in a single swoop!

How It Works

Think of this as a complex number calculator:

  • Step 1: Parse Strings:
    • Split each string at '+' to separate real and imaginary parts.
    • Convert "a" and "bi" (remove 'i') to integers.
  • Step 2: Multiply:
    • For (a + bi)(c + di):
      • Real part = ac - bd.
      • Imaginary part = ad + bc.
  • Step 3: Format Result:
    • Return "real+imaginaryi".
  • Why It Works:
    • String format is fixed, parsing is simple.
    • Math follows complex number rules.

It’s like a complex number cruncher!

Step-by-Step Example

Example: num1 = "1+1i", num2 = "1+1i"

  • Step 1: Parse:
    • num1: "1+1i" → ["1", "1i"], real1 = 1, imag1 = 1.
    • num2: "1+1i" → ["1", "1i"], real2 = 1, imag2 = 1.
  • Step 2: Multiply:
    • Real = (1 1) - (1 1) = 1 - 1 = 0.
    • Imag = (1 1) + (1 1) = 1 + 1 = 2.
  • Step 3: Format:
    • "0+2i".
  • Result: "0+2i".

Example: num1 = "1+-2i", num2 = "1+-2i"

  • Parse:
    • num1: "1+-2i" → ["1", "-2i"], real1 = 1, imag1 = -2.
    • num2: "1+-2i" → ["1", "-2i"], real2 = 1, imag2 = -2.
  • Multiply:
    • Real = (1 1) - (-2 -2) = 1 - 4 = -3.
    • Imag = (1 -2) + (1 -2) = -2 - 2 = -4.
  • Format: "-3+-4i".
  • Result: "-3+-4i".

Code with Detailed Line-by-Line Explanation

Here’s the Python code, explained for beginners:

class Solution:
    def complexNumberMultiply(self, num1: str, num2: str) -> str:
        # Step 1: Parse num1
        real1, imag1 = num1.split('+')
        real1 = int(real1)
        imag1 = int(imag1[:-1])  # Remove 'i'

        # Step 2: Parse num2
        real2, imag2 = num2.split('+')
        real2 = int(real2)
        imag2 = int(imag2[:-1])  # Remove 'i'

        # Step 3: Multiply
        real_part = real1 * real2 - imag1 * imag2  # (ac - bd)
        imag_part = real1 * imag2 + imag1 * real2  # (ad + bc)

        # Step 4: Format result
        return f"{real_part}+{imag_part}i"
  • Lines 4-6: Split num1 at '+', convert real to int, imaginary to int (remove 'i').
  • Lines 9-11: Same for num2.
  • Lines 14-15: Compute real and imaginary parts using complex multiplication formula.
  • Line 18: Format as "a+bi" using f-string.
  • Time Complexity: O(1)—string parsing and math are constant time (bounded input).
  • Space Complexity: O(1)—few variables.

It’s like a complex string multiplier!

Alternative Solution: Split and Recombine Approach

Section link icon

Why an Alternative Approach?

The split and recombine approach breaks the problem into more explicit steps, splitting strings, handling signs manually, and recombining parts, still in O(1) time and O(1) space. It’s slightly more verbose but very clear, making it great for beginners who prefer step-by-step logic.

How It Works

Picture this as a complex number assembler:

  • Step 1: Split at '+' and 'i', handle signs.
  • Step 2: Extract real and imaginary parts as integers.
  • Step 3: Multiply using formula.
  • Step 4: Recombine into string.

It’s like a complex number kit!

Step-by-Step Example

Example: num1 = "1+-2i", num2 = "1+-2i"

  • Step 1: Split:
    • num1: "1+-2i" → ["1", "-2i"] → real1 = "1", imag1 = "-2".
    • num2: "1+-2i" → ["1", "-2i"] → real2 = "1", imag2 = "-2".
  • Step 2: Convert:
    • real1 = 1, imag1 = -2.
    • real2 = 1, imag2 = -2.
  • Step 3: Multiply:
    • Real = 1 1 - (-2 -2) = 1 - 4 = -3.
    • Imag = 1 -2 + (-2 1) = -2 - 2 = -4.
  • Step 4: Recombine: "-3+-4i".
  • Result: "-3+-4i".

Code for Split Approach

class Solution:
    def complexNumberMultiply(self, num1: str, num2: str) -> str:
        # Step 1: Split and extract parts
        def parse_complex(num):
            parts = num.split('+')
            real = int(parts[0])
            imag = int(parts[1].replace('i', ''))
            return real, imag

        # Step 2: Parse both numbers
        real1, imag1 = parse_complex(num1)
        real2, imag2 = parse_complex(num2)

        # Step 3: Multiply
        real_part = real1 * real2 - imag1 * imag2
        imag_part = real1 * imag2 + imag1 * real2

        # Step 4: Recombine
        return str(real_part) + '+' + str(imag_part) + 'i'
  • Lines 4-7: Parse helper splits, converts parts.
  • Lines 10-11: Parse both inputs.
  • Lines 14-15: Compute product.
  • Line 18: Build result string.
  • Time Complexity: O(1)—constant operations.
  • Space Complexity: O(1)—few variables.

It’s a step-by-step multiplier!

Comparing the Two Solutions

Section link icon
  • Direct Parsing (Best):
    • Pros: O(1), O(1), concise.
    • Cons: Inline parsing.
  • Split and Recombine (Alternative):
    • Pros: O(1), O(1), explicit steps.
    • Cons: More verbose.

Direct parsing wins for brevity!

Additional Examples and Edge Cases

Section link icon
  • "0+0i", "1+1i": "0+0i".
  • "1+0i", "0+1i": "0+1i".
  • "-1+-1i", "2+2i": "-4+0i".

Direct parsing handles them all!

Complexity Recap

Section link icon
  • Direct Parsing: Time O(1), Space O(1).
  • Split and Recombine: Time O(1), Space O(1).

Direct parsing’s the clarity champ!

Key Takeaways

Section link icon
  • Direct Parsing: Quick and clean—learn at Python Basics!
  • Split: Step-by-step clarity.
  • Strings: Math meets parsing.
  • Python: Split and format shine!

Final Thoughts: Multiply Those Complexes!

Section link icon

LeetCode 537: Complex Number Multiplication in Python is a fun string-math challenge. Direct parsing and multiplication is your fast track, while split and recombine offers a clear alternative. Want more? Try LeetCode 43: Multiply Strings or LeetCode 67: Add Binary. Ready to multiply? Head to Solve LeetCode 537 on LeetCode and crunch those complex numbers today!