Talentd
FleetCode
Make and follow sheets.Sign in

Complex Number Multiplication solution and explanation

MediumMathSimulationString5 min read73.9% acceptanceUpdated 9 Apr 2026
Complex Number Multiplication | LeetCodeKnowledge Amplifier · 7:37 · 2K viewsWatch on YouTube
9 more videos on this problem
  1. Complex Number Multiplication | LeetCodeKnowledge Amplifier · 7:37 · 2K views
  2. Leetcode - Complex Number Multiplication (Python)Timothy H Chang · 3:40 · 1K views
  3. Complex Number Multiplication | Leetcode Complex Number Multiplication 537 | Live coding session 🔥🔥🔥Coding Decoded · 9:30 · 936 views
  4. 537. Complex Number Multiplication | LEETCODE MEDIUM | MATHScode Explainer · 4:51 · 447 views
  5. Daily Leetcode #511: Aug 24, 2021 - 537. Complex Number MultiplicationProgramming Live with Larry · 11:22 · 281 views
  6. Leetcode [537] Complex Number MultiplicationSDE Skills · 6:46 · 256 views
  7. 537. Complex Number Multiplication - Daily Leetcode (Day 1)yeetcode · 10:57 · 232 views
  8. LeetCode 537. Complex Number Multiplication Solution Explained - JavaAlgorithms and Data Structures Course · 7:06 · 211 views
  9. Complex Number Multiplication Leetcode 537 || Coding Culture || Daily Challenge5 Minutes Code · 9:34 · 185 views
  10. Complex Number Multiplication | Leetcode 537 | String | Medium | PythonAmitav Edutech · 8:07 · 185 views

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].
  • i2 == -1.

Given two complex numbers num1 and num2 as strings, return a string of the complex number that represents their multiplications.

Example 1:

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.

Example 2:

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.

Constraints:

  • num1 and num2 are valid complex numbers.

Approach overview

Problem Overview: You receive two complex numbers formatted as strings like "a+bi". The task is to multiply them and return the result in the same format. You must parse the real and imaginary components, apply the complex multiplication rule, and format the output string.

Complex multiplication follows a fixed formula: (a + bi)(c + di) = (ac − bd) + (ad + bc)i. The challenge is not the math itself but reliably extracting integers from the string representation.

Approach 1: Parse and Multiply Components (O(n) time, O(1) space)

The most straightforward approach is manual string parsing. Split the input around the '+' character to separate the real part and the imaginary component. Then strip the trailing 'i' and convert both parts to integers. Once you have a, b, c, and d, apply the formula (ac − bd) for the real part and (ad + bc) for the imaginary part. Finally, concatenate the result back into the "x+yi" format.

This approach uses basic string operations such as split(), substring slicing, and integer conversion. The parsing step scans each string once, giving O(n) time where n is the string length, and O(1) extra space. This method is simple, language‑agnostic, and easy to implement in C, C++, Java, Python, C#, and JavaScript.

Approach 2: Regular Expression Parsing (O(n) time, O(1) space)

Another clean option is extracting the real and imaginary values using a regular expression. A pattern like (-?\d+)\+(-?\d+)i captures both numeric components directly. Once matched, convert the captured groups into integers and apply the same multiplication formula.

This approach reduces manual string manipulation and keeps the parsing logic concise. The regex engine scans the string once, so the complexity remains O(n) time with O(1) additional space. It fits well in languages with strong regex support such as Python or JavaScript. The core computation still relies on simple math operations and basic simulation of the formula.

Recommended for interviews: The manual parsing approach is typically expected. Interviewers want to see that you understand the complex number formula and can reliably extract components from a formatted string. Regex parsing is equally correct but sometimes viewed as overkill for such a predictable format. Showing the formula implementation clearly demonstrates both string handling and mathematical reasoning.

Approach 1: Parse and Multiply Components

This approach involves parsing the given strings to separate the real and imaginary components of each complex number. Once separated, apply the distributive property of multiplication for complex numbers: (a+bi)(c+di) = ac + adi + bci + bdi^2. Substitute i^2 with -1 and then combine the real and imaginary parts for the final output string.

def parse_complex(complex):
    real, imag = complex.split('+')
    imag = imag.rstrip('i')
    return int(real), int(imag)

def complexNumberMultiply(num1, num2):
    real1, imag1 = parse_complex(num1)
    real2, imag2 = parse_complex(num2)

    real_part = real1 * real2 - imag1 * imag2
    imag_part = real1 * imag2 + imag1 * real2

    return f"{real_part}+{imag_part}i"

# Example usage
num1 = "1+1i"
num2 = "1+1i"
print(complexNumberMultiply(num1, num2))
public class ComplexNumber {
    private int real, imag;

    public ComplexNumber(String complex) {
        String[] parts = complex.split("[+i]");
        this.real = Integer.parseInt(parts[0]);
        this.imag = Integer.parseInt(parts[1]);
    }

    public static String complexNumberMultiply(String num1, String num2) {
        ComplexNumber c1 = new ComplexNumber(num1);
        ComplexNumber c2 = new ComplexNumber(num2);

        int realPart = c1.real * c2.real - c1.imag * c2.imag;
        int imagPart = c1.real * c2.imag + c1.imag * c2.real;

        return realPart + "+" + imagPart + "i";
    }

    public static void main(String[] args) {
        String num1 = "1+1i";
        String num2 = "1+1i";
        System.out.println(complexNumberMultiply(num1, num2));
    }
}
#include <iostream>
#include <string>
#include <sstream>

void parseComplex(const std::string& complex, int& real, int& imaginary) {
    char plus, i;
    std::istringstream iss(complex);
    iss >> real >> plus >> imaginary >> i;
}

std::string complexNumberMultiply(std::string num1, std::string num2) {
    int real1, imag1, real2, imag2;
    parseComplex(num1, real1, imag1);
    parseComplex(num2, real2, imag2);
    
    int realPart = real1 * real2 - imag1 * imag2;
    int imagPart = real1 * imag2 + imag1 * real2;
    
    return std::to_string(realPart) + "+" + std::to_string(imagPart) + "i";
}

int main() {
    std::string num1 = "1+1i";
    std::string num2 = "1+1i";
    std::cout << complexNumberMultiply(num1, num2) << std::endl;
    return 0;
}
function parseComplex(complex) {
    let parts = complex.replace('i', '').split('+');
    return [parseInt(parts[0]), parseInt(parts[1])];
}

function complexNumberMultiply(num1, num2) {
    let [real1, imag1] = parseComplex(num1);
    let [real2, imag2] = parseComplex(num2);

    let realPart = real1 * real2 - imag1 * imag2;
    let imagPart = real1 * imag2 + imag1 * real2;

    return `${realPart}+${imagPart}i`;
}

// Example usage
let num1 = "1+1i";
let num2 = "1+1i";
console.log(complexNumberMultiply(num1, num2));
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void parseComplex(const char *complex, int *real, int *imaginary) {
    sscanf(complex, "%d+%di", real, imaginary);
}

char* complexNumberMultiply(const char* num1, const char* num2) {
    int real1, imag1, real2, imag2;
    parseComplex(num1, &real1, &imag1);
    parseComplex(num2, &real2, &imag2);
    
    int realPart = real1 * real2 - imag1 * imag2;
    int imagPart = real1 * imag2 + imag1 * real2;
    
    char *result = malloc(20);
    sprintf(result, "%d+%di", realPart, imagPart);
    return result;
}

int main() {
    char num1[] = "1+1i";
    char num2[] = "1+1i";
    char* result = complexNumberMultiply(num1, num2);
    printf("%s\n", result);
    free(result);
    return 0;
}
using System;

class ComplexNumber {
    public int Real { get; }
    public int Imaginary { get; }

    public ComplexNumber(string complex) {
        var parts = complex.Split('+');
        Real = int.Parse(parts[0]);
        Imaginary = int.Parse(parts[1].TrimEnd('i'));
    }

    public static string ComplexNumberMultiply(string num1, string num2) {
        var c1 = new ComplexNumber(num1);
        var c2 = new ComplexNumber(num2);

        int realPart = c1.Real * c2.Real - c1.Imaginary * c2.Imaginary;
        int imagPart = c1.Real * c2.Imaginary + c1.Imaginary * c2.Real;

        return $"{realPart}+{imagPart}i";
    }

    static void Main() {
        string num1 = "1+1i";
        string num2 = "1+1i";
        Console.WriteLine(ComplexNumberMultiply(num1, num2));
    }
}

Python's string processing abilities make it easy to split the complex number into its components. The split method is used to separate the real and imaginary parts. After computing these parts using the complex multiplication formula, the result is formatted into the expected form using an f-string.

Complexity

Time Complexity: O(1) because operations involve fixed-size integers.
Space Complexity: O(1) as it utilizes only a small constant amount of extra space.

Try this approach in the editor

Approach 2: Regular Expression Parsing

In this approach, regular expressions are used to parse the complex number strings. This involves defining a regex pattern to capture the real and imaginary components. After extracting these components, multiplication is performed using the same algebraic rules, and the result is formatted for output.

import re

def parse_complex_regex(complex):
    match = re.match(r'(-?\d+)\+(-?\d+)i', complex)
    return int(match.group(1)), int(match.group(2))

def complexNumberMultiply(num1, num2):
    real1, imag1 = parse_complex_regex(num1)
    real2, imag2 = parse_complex_regex(num2)

    real_part = real1 * real2 - imag1 * imag2
    imag_part = real1 * imag2 + imag1 * real2

    return f"{real_part}+{imag_part}i"

# Example usage
num1 = "1+1i"
num2 = "1+1i"
print(complexNumberMultiply(num1, num2))
function parseComplexRegex(complex) {
    const matches = complex.match(/(-?\d+)\+(-?\d+)i/);
    return [parseInt(matches[1]), parseInt(matches[2])];
}

function complexNumberMultiply(num1, num2) {
    const [real1, imag1] = parseComplexRegex(num1);
    const [real2, imag2] = parseComplexRegex(num2);

    const realPart = real1 * real2 - imag1 * imag2;
    const imagPart = real1 * imag2 + imag1 * real2;

    return `${realPart}+${imagPart}i`;
}

// Example usage
let num1 = "1+1i";
let num2 = "1+1i";
console.log(complexNumberMultiply(num1, num2));

Using re.match in Python with a regular expression captures the real and imaginary parts directly. The parsed integers are used for multiplication, with results formatted back into strings in the expected form using Python's f-string syntax.

Complexity

Time Complexity: O(1) since the regex operation is effectively constant time for fixed-size strings.
Space Complexity: O(1) involving fixed-size auxiliary storage for components and result.

Try this approach in the editor

Approach 3: Simulation

We can convert the complex number string into its real part a and imaginary part b, and then use the formula for complex number multiplication (a_1 + b_1i) times (a_2 + b_2i) = (a_1a_2 - b_1b_2) + (a_1b_2 + a_2b_1)i to calculate the result.

The time complexity is O(1), and the space complexity is O(1).

function complexNumberMultiply(num1: string, num2: string): string {
    const [a1, b1] = num1.slice(0, -1).split('+').map(Number);
    const [a2, b2] = num2.slice(0, -1).split('+').map(Number);
    return `${a1 * a2 - b1 * b2}+${a1 * b2 + a2 * b1}i`;
}
func complexNumberMultiply(num1 string, num2 string) string {
	x, _ := strconv.ParseComplex(num1, 64)
	y, _ := strconv.ParseComplex(num2, 64)
	return fmt.Sprintf("%d+%di", int(real(x*y)), int(imag(x*y)))
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Parse and Multiply Components

Time Complexity: O(1) because operations involve fixed-size integers.
Space Complexity: O(1) as it utilizes only a small constant amount of extra space.

Regular Expression Parsing

Time Complexity: O(1) since the regex operation is effectively constant time for fixed-size strings.
Space Complexity: O(1) involving fixed-size auxiliary storage for components and result.

Simulation–

Complexity analysis

ApproachTimeSpaceWhen to Use
Parse and Multiply ComponentsO(n)O(1)Best general solution. Clear logic using split and integer conversion.
Regular Expression ParsingO(n)O(1)Useful when regex is preferred for structured string extraction.

Frequently asked questions

Is Complex Number Multiplication easy or hard?

The problem is rated Medium because the math formula is simple but careful string parsing is required. Handling negative numbers, extracting the imaginary part correctly, and formatting the output string are the main points where mistakes happen.

Complex Number Multiplication Python/Java solution

Both Python and Java implementations follow the same idea: split the string at '+', remove the trailing 'i', convert values to integers, then compute (ac − bd) and (ad + bc). Python typically uses split() and slicing, while Java often uses split("\\+") and substring operations.

How to solve Complex Number Multiplication in O(n)?

Parse the string "a+bi" into two integers: the real part a and the imaginary part b. Repeat for the second number to obtain c and d. Compute the result using (ac − bd) for the real component and (ad + bc) for the imaginary component, then format the output as "x+yi".

What is the best approach for Complex Number Multiplication?

The most practical approach is parsing the real and imaginary parts using string split operations and then applying the formula (ac − bd) + (ad + bc)i. This runs in O(n) time for string parsing and O(1) space. It is straightforward, language‑agnostic, and commonly expected in coding interviews.

Is Complex Number Multiplication asked at Google/Amazon/Meta?

String parsing and math‑simulation problems similar to this appear in interviews at large tech companies, especially in early or mid‑level coding rounds. The problem tests attention to detail, correct parsing, and applying a known mathematical formula correctly.

What data structure is used in Complex Number Multiplication?

No advanced data structures are required. The solution primarily uses basic string manipulation, integer variables, and arithmetic operations. Some implementations optionally use regular expressions for structured string parsing.

What is the time complexity of Complex Number Multiplication?

The overall complexity is O(n) where n is the length of the input string. The algorithm scans each string once to extract the numeric components, followed by constant‑time arithmetic operations. Space complexity stays O(1) since only a few integer variables are stored.

Comments

Now write it yourselfClose this page and solve Complex Number Multiplication in the editor, without looking.
Practise Complex Number Multiplication