Data Structures & AlgorithmsModerateProduct Company SDE · Amazon-style OA

Problem: Return, for each index i, the product of all other elements (no division allowed). Print the list for a = [2, 3, 4, 5].

Problem: Return, for each index i, the product of all other elements (no division allowed). Print the list for a = [2, 3, 4, 5].
a = [2, 3, 4, 5]
pre = [1] * len(a)
suf = [1] * len(a)
for i in range(1, len(a)):
    pre[i] = pre[i - 1] * a[i - 1]
for i in range(len(a) - 2, -1, -1):
    suf[i] = suf[i + 1] * a[i + 1]
print([pre[i] * suf[i] for i in range(len(a))])
What is printed?
  1. A. [120, 60, 40, 30]
  2. B. [60, 40, 30, 20]
  3. C. [24, 30, 40, 60]
  4. D. [60, 40, 30, 24]

Correct answer: D. [60, 40, 30, 24]

Prefix and suffix products multiply to the product of everything except the current element. For index 0 it is 3 * 4 * 5 = 60, and index 3 gives 2 * 3 * 4 = 24.

More Coding Interview Problems questions

Exams that ask this topic