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?- A. [0, 30, 0, 0]
- B. [0, 0, 0, 0]
- C. [15, 30, 6, 10]
- 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
- Problem: Given an array where values lie in 1..n, find the value that appears twice (exactly one does) without modifying the array. python…
- Problem: Given n ≤ 10⁵ integers (not sorted), find the length of the longest run of consecutive values, e.g. [100, 4, 200, 1, 3, 2] → 4…
- Problem: Group words that are anagrams of each other and report how many groups there are. python from collections import defaultdict def…
- Problem: Count the number of contiguous subarrays whose sum equals k. Values can be negative. python def countk(a, k): seen = {0: 1} p =…
- Problem: Count subarrays whose sum is divisible by k (values may be negative). python def divk(a, k): cnt = [0] k cnt[0] = 1 p = ans = 0…
- Problem: For n ≤ 2 × 10⁵ integers in the range −10⁴..10⁴, count subarrays with sum exactly k. Why does a two-pointer sliding window NOT…