Data Structures & AlgorithmsHardTCS Digital · Infosys SP

Product of all elements except self, using prefix and suffix products (no division). What is printed?

Product of all elements except self, using prefix and suffix products (no division). What is printed?
a = [-1, 0, 2, 2, 2]
n = len(a); out = [1] * n
p = 1
for i in range(n): out[i] = p; p *= a[i]
s = 1
for i in range(n - 1, -1, -1): out[i] *= s; s *= a[i]
print(out)
  1. A. [0, −8, 0, 0, 0]
  2. B. [−8, 0, 0, 0, 0]
  3. C. [0, 0, −8, 0, 0]
  4. D. [0, 0, 0, 0, 0]

Correct answer: A. [0, −8, 0, 0, 0]

out[i] must take the product BEFORE multiplying in a[i]; a zero in the array makes every other position 0 except the zero's own. Output: [0, −8, 0, 0, 0].

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic