algoadvance

Leetcode 537. Complex Number Multiplication

Problem Statement

Given two strings representing two complex numbers, you need to return a string representing their multiplication. Note that the complex numbers are provided in the form a+bi where a and b are integers, and i represents the imaginary unit.

Clarifying Questions

  1. Q: What are the valid ranges for the integers a and b?
    • A: The problem does not specify bounds, so we should assume they can fit within standard integer ranges.
  2. Q: Are the inputs guaranteed to be valid complex numbers in the form a+bi?
    • A: Yes, you can assume the inputs will always be in the correct format as specified.
  3. Q: How should the result be formatted?
    • A: The result should also be in the form c+di where c and d are integers representing the real and imaginary parts, respectively.

Strategy

  1. Parse the Input Strings: Extract the real and imaginary parts from each input string.
  2. Extract Integers: Use string manipulation to isolate the integer values a, b, c, and d.
  3. Complex Multiplication: Use the formula for multiplying complex numbers (a + bi) * (c + di) = (ac - bd) + (ad + bc)i.
  4. Construct the Result: Format the result as c+di.

Code

#include <iostream>
#include <string>
using namespace std;

pair<int, int> parseComplexNumber(const string& complex) {
    size_t plusPos = complex.find('+');
    size_t iPos = complex.find('i');
    
    int realPart = stoi(complex.substr(0, plusPos));
    int imagPart = stoi(complex.substr(plusPos + 1, iPos - plusPos - 1));
    
    return {realPart, imagPart};
}

string complexNumberMultiply(string num1, string num2) {
    pair<int, int> complex1 = parseComplexNumber(num1);
    pair<int, int> complex2 = parseComplexNumber(num2);
    
    int a = complex1.first;
    int b = complex1.second;
    int c = complex2.first;
    int d = complex2.second;
    
    int realPart = (a * c) - (b * d);
    int imagPart = (a * d) + (b * c);
    
    return to_string(realPart) + "+" + to_string(imagPart) + "i";
}

int main() {
    // Test case
    string num1 = "1+1i";
    string num2 = "1+1i";
    cout << complexNumberMultiply(num1, num2) << endl; // Output should be "0+2i"
    return 0;
}

Explanation

  1. Function parseComplexNumber: This helper function takes a string in the form a+bi, splits it into the real part and the imaginary part, and returns them as a pair<int, int>.
  2. Function complexNumberMultiply: This main function first parses inputs to extract real and imaginary parts. It then applies the complex multiplication formula to compute the real and imaginary parts of the result, and finally constructs the result string.

Time Complexity

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI