Complex Number Multiplication — LeetCode 537 Python Solution

MediumMathStringSimulation
Problem
#537
Reading time
2 min

The problem

A complex number can be represented as a string on the form "real+imaginaryi" 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].

Example

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.

Python solution

Python
class Solution:
    def complexNumberMultiply(self, num1: str, num2: str) -> str:
        a1, b1 = map(int, num1[:-1].split("+"))
        a2, b2 = map(int, num2[:-1].split("+"))
        return f"{a1 * a2 - b1 * b2}+{a1 * b2 + a2 * b1}i"

Complexity

MeasureComplexity
TimeO(1)
SpaceO(1) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 537. Complex Number Multiplication is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 537. Complex Number Multiplication?
LeetCode 537. Complex Number Multiplication is rated Medium on LeetCode.
What is the time complexity of LeetCode 537. Complex Number Multiplication?
The Python solution on this page runs in O(1).
What is the space complexity of LeetCode 537. Complex Number Multiplication?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 537. Complex Number Multiplication cover?
LeetCode 537. Complex Number Multiplication is tagged Math, String and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview