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"
Difficulty
and has an acceptance rate of about 74% (100k+ submissions).
Typical patterns to solve this problem:
- Math
- Simulation
- String
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
Other Solutions
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++ |
Videos
Solved On The Same Day
- problem 889: Construct Binary Tree from Preorder and Postorder Traversal
- problem 1706: Where Will the Ball Fall
- problem 1850: Minimum Adjacent Swaps to Reach the Kth Smallest Number
- problem 1172: Dinner Plate Stacks
Extra
- 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