Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Return, for every index i, the product of all elements except a[i], without using division. Example: [1, 2, 3, 4] → [24, 12, 8, 6].

Problem: Return, for every index i, the product of all elements except a[i], without using division. Example: [1, 2, 3, 4] → [24, 12, 8, 6].
def prod_except(a):
    n = len(a)
    out = [1] * n
    left = 1
    for i in range(n):
        out[i] = left
        left *= a[i]
    right = 1
    for i in range(n - 1, -1, -1):
        out[i] *= right
        right *= a[i]
    return out
print(prod_except([2, 0, 5, 3]))
What is printed?
  1. A. [0, 30, 0, 0]
  2. B. [0, 0, 0, 0]
  3. C. [15, 30, 6, 10]
  4. D. [0, 30, 0, 10]

Correct answer: A. [0, 30, 0, 0]

out[i] = (product of the left part) × (product of the right part). Only index 1, which excludes the zero, gets 2 × 5 × 3 = 30; every other position includes the 0. The division trick total / a[i] fails here because of the zero. O(n) time, O(1) extra space besides the output.

More Coding Interview Problems questions

Exams that ask this topic