Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern

Problem: Multiply two non-negative integers given as decimal strings without converting them to int; digit i·j lands in position i + j + 1 of the result buffer.

Problem: Multiply two non-negative integers given as decimal strings without converting them to int; digit i·j lands in position i + j + 1 of the result buffer.
def mul(a, b):
    res = [0] * (len(a) + len(b))
    for i in range(len(a) - 1, -1, -1):
        for j in range(len(b) - 1, -1, -1):
            p = int(a[i]) * int(b[j]) + res[i + j + 1]
            res[i + j + 1] = p % 10; res[i + j] += p // 10
    return "".join(map(str, res)).lstrip("0") or "0"
print(mul("99", "99"), mul("123", "0"), mul("25", "4"))
What is printed?
  1. A. 9801 0 0100
  2. B. 9801 000 100
  3. C. 981 0 100
  4. D. 9801 0 100

Correct answer: D. 9801 0 100

A product of an m-digit and an n-digit number has at most m + n digits, so the buffer never overflows. Carries move into res[i + j]. Leading zeros are stripped, but an all-zero result must still return "0" (the 'or' handles 123 × 0). O(m·n).

More Coding Interview Problems questions

Exams that ask this topic