algoadvance

Leetcode 537. Complex Number Multiplication

Problem Statement

You are given two strings representing two complex numbers:

Function Signature

public String complexNumberMultiply(String num1, String num2)

Example

Input: num1 = "1+1i", num2 = "1+1i"
Output: "0+2i"

Input: num1 = "1+-1i", num2 = "1+-1i"
Output: "0+-2i"

Clarifying Questions

  1. Input Format: Should I consider inputs always in the correct format (i.e., no invalid characters or misplaced signs)?
    • Assumption: Yes, inputs will always be in valid format as specified.
  2. Range of Values: Is there a range for the integer values (a) or (b)?
    • Assumption: Given values for (a) and (b) are within the range for Java’s int type.

Strategy

  1. Parse the Input: Extract the real and imaginary parts from both input strings separately.
  2. Apply Multiplication Formula: Use the algebraic formula for multiplying two complex numbers ((a + bi)(c + di) = (ac - bd) + (ad + bc)i).
  3. Construct the Output: Combine the resultant parts into the required string format and return it.

Code

public class ComplexNumberMultiplication {
    public String complexNumberMultiply(String num1, String num2) {
        // Parse both complex numbers
        int[] complex1 = parseComplexNumber(num1);
        int[] complex2 = parseComplexNumber(num2);
        
        int a = complex1[0], b = complex1[1];
        int c = complex2[0], d = complex2[1];
        
        // Apply the complex number multiplication formula
        int realPart = a * c - b * d;
        int imaginaryPart = a * d + b * c;
        
        // Construct the result in "real+imaginaryi" format
        return realPart + "+" + imaginaryPart + "i";
    }
    
    // Helper method to parse a complex number string into its real and imaginary parts
    private int[] parseComplexNumber(String num) {
        String[] parts = num.split("\\+");
        int realPart = Integer.parseInt(parts[0]);
        int imaginaryPart = Integer.parseInt(parts[1].replace("i", ""));
        return new int[]{realPart, imaginaryPart};
    }

    // Sample usage
    public static void main(String[] args) {
        ComplexNumberMultiplication sol = new ComplexNumberMultiplication();
        System.out.println(sol.complexNumberMultiply("1+1i", "1+1i")); // Output: "0+2i"
        System.out.println(sol.complexNumberMultiply("1+-1i", "1+-1i")); // Output: "0+-2i"
    }
}

Time Complexity

Overall, the time complexity is O(n).

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