43. Multiply Strings

MathStringSimulation

Explanation

To multiply two numbers represented as strings num1 and num2, we can simulate the multiplication process that we do manually. We iterate through each digit of num1 from right to left and multiply it with each digit of num2 from right to left. We keep track of the product at each position and then sum up all these intermediate products to get the final result.

Algorithmic Idea

  1. Initialize a result array of size num1.length() + num2.length().
  2. Iterate through each digit of num1 from right to left.
  3. Iterate through each digit of num2 from right to left.
  4. Multiply the current digits and add the product to the appropriate position in the result array.
  5. After both loops finish, convert the result array to a string while handling any leading zeros.

Time Complexity

The time complexity of this algorithm is O(m * n), where m is the length of num1 and n is the length of num2.

Space Complexity

The space complexity of this algorithm is O(m + n) to store the result array.

class Solution {
    public String multiply(String num1, String num2) {
        int m = num1.length(), n = num2.length();
        int[] result = new int[m + n];

        for (int i = m - 1; i >= 0; i--) {
            for (int j = n - 1; j >= 0; j--) {
                int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
                int sum = mul + result[i + j + 1];
                result[i + j] += sum / 10;
                result[i + j + 1] = sum % 10;
            }
        }

        StringBuilder sb = new StringBuilder();
        for (int num : result) {
            if (!(sb.length() == 0 && num == 0)) {
                sb.append(num);
            }
        }

        return sb.length() == 0 ? "0" : sb.toString();
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.