Problem 537

Abstract / Summary

Given two strings representing complex numbers multiply them and return the result as a string in the same format

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0537.py

class Solution:
    def complexNumberMultiply(self, num1: str, num2: str) -> str:
        # parse complex number string
        def get(s):
            real, imaginary = s.split("+")
            return int(real), int(imaginary[: -1]) # strip "i", too

        r1, i1 = get(num1)
        r2, i2 = get(num2)

        #     num1    *   num2
        # = (r1 + i1*i) * (r2 + i2*i)
        # = r1*r2 + r1*i2*i + i1*r2*i + i1*i2*i*i   => i*i = -1
        # = r1*r2 - i1*i2 + i * (r1*i2 + i1*r2)
        r3 = r1 * r2 - i1 * i2
        i3 = r1 * i2 + i1 * r2

        return f"{r3}+{i3}i"
18 lines | 598 bytes | submitted March 22, 2024 | GitHub   60% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 74% (100k+ submissions).

Typical patterns to solve this problem:
  • Math
  • Simulation
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a single method that receives two complex numbers encoded as strings, multiplies them, and returns the result in the same string format. The logic is divided into three conceptual phases: parsing the input strings, applying the algebraic formula for complex multiplication, and constructing the output string.

Parsing the Input

The inner helper get isolates the real and imaginary components of a complex number.

def get(s):
    real, imaginary = s.split("+")
    return int(real), int(imaginary[:-1])   # strip trailing 'i'

The split operation separates the substring before the plus sign (the real part) from the substring after it (the imaginary part with a trailing i). Converting both substrings to int yields numeric values that can be used directly in arithmetic. This approach correctly interprets negative values because the sign is retained in the substring (e.g., "1+-2i" becomes "1" and "-2i").

Computing the Product

After extracting the components, the method applies the standard formula for multiplying two complex numbers:

[ (r_1 + i_1 i) \times (r_2 + i_2 i) = (r_1 r_2 - i_1 i_2) + (r_1 i_2 + i_1 r_2)i ]

The code implements this formula with straightforward integer arithmetic:

r3 = r1 * r2 - i1 * i2
i3 = r1 * i2 + i1 * r2

Both intermediate results are computed using only primitive operations, ensuring that the calculation remains fast and deterministic regardless of the magnitude of the operands.

Formatting the Result

The final step converts the numeric result back into the required string representation:

return f"{r3}+{i3}i"

The f-string concatenates the real part, a plus sign, the imaginary part, and the trailing i. Because i3 may be negative, the resulting string naturally contains the sign (e.g., "3+-4i"), matching the input format.

Edge Cases Handled

  • Zero Components - When either the real or imaginary part is zero, the arithmetic still yields correct values, and the formatted string reflects the zero ("0+5i" or "7+0i").
  • Negative Values - The parsing logic retains the sign for both real and imaginary components, allowing inputs such as "-3+-2i" to be processed without additional checks.
  • Large Integers - Python’s arbitrary-precision integers mean that the multiplication works for values far beyond typical 32-bit limits, with no overflow concerns.
  • Minimal Input Length - Even the shortest valid representation ("0+0i") is correctly split and converted, producing "0+0i" as the output.

Performance Optimizations

The implementation avoids any auxiliary data structures; all intermediate values are simple scalar variables. The parsing step uses a single split call and slicing to discard the trailing i, which is a constant-time operation. The multiplication itself consists of four integer multiplications and two additions/subtractions, all executed in place. Consequently, the method runs with minimal overhead and constant memory usage, making it well-suited for high-throughput scenarios where many complex multiplications are required.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have two special boxes, and each box contains a pair of secret numbers. These numbers represent complex math, which is just a fancy name for a pair of friends who like to stick together. Inside the computer code, there is a tiny helper called a function. This helper reaches into the first box and pulls out the two parts of the first number. Then the helper does the same thing with the second box.

Once the four numbers are sitting on the table, the computer follows a specific set of rules to multiply them. When complex numbers meet, they mix together in a special way. The parts that do not have any special stickers get multiplied to make the new starting number. The parts that do have stickers interact, and because of a funny rule in math, they actually flip their sign. Finally, the different pieces are added back together to create a brand new pair of numbers. The last step is putting those two new numbers into a new, single box so they look just like the ones you started with.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 7.81 | σ = 1.11

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Go TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
halfrost Go
JoshCrozier JS
keineahnung2345 C++
linouk23 C++
lkwq007 Python
lzl124631x C++
ruoru Rust
suxrobGM C#
varunu28 Java
yuanliu666 Kotlin
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
linouk23 C++
lkwq007 Python
lzl124631x C++
ruoru Rust
suxrobGM C#
varunu28 Java
yuanliu666 Kotlin
zfang399 C++
32 links | 19 authors | 9 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

5 solutions   March 22, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality