↻one more pass.
Math & geometry · Medium

Multiply Strings: the idea to remember.

Multiply two nonnegative integers written as decimal strings without parsing the whole values into built in integer types.

Solve on LeetCode ↗

The core insight

Accumulate each pair of digit products into its place value and propagate decimal carries.

Why it works

Digits at indices i and j contribute to position i plus j plus one, with carry into the position before it.

The mistake to avoid

Strip leading zeros but return exactly one zero for a zero result. Do not parse long strings into int or long.

Time: O(m · n)Space: O(m+n)

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

String multiply(String first, String second) {
    int[] digits = new int[first.length() + second.length()];
    for (int i = first.length()-1; i >= 0; i--) {
        for (int j = second.length()-1; j >= 0; j--) {
            int position = i + j + 1;
            int sum = digits[position] + (first.charAt(i)-'0') * (second.charAt(j)-'0');
            digits[position] = sum % 10;
            digits[position-1] += sum / 10;
        }
    }
    StringBuilder result = new StringBuilder();
    for (int digit : digits) if (result.length() != 0 || digit != 0) result.append(digit);
    return result.length() == 0 ? "0" : result.toString();
}

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.