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?- A. [120, 60, 40, 30]
- B. [60, 40, 30, 20]
- C. [24, 30, 40, 60]
- 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
- Problem: How many distinct non-empty substrings does the string 'abab' contain? python s = 'abab' print(len({s[i:j] for i in range(len(s))…
- Problem: What is the maximum XOR of any two different elements of the array [3, 10, 5, 25, 2, 8]? python a = [3, 10, 5, 25, 2, 8]…
- Problem: What is the length of the longest contiguous subarray containing at most two distinct values? python from collections import…
- Problem: Remove exactly 3 digits from the number '1432219' to make the smallest possible number, keeping the remaining digits in order…
- Problem: What is the length of the longest palindromic subsequence of 'bbbab'? python def lps(s): n = len(s) dp = [[0] n for in range(n)]…
- Problem: Multiply a chain of matrices with dimensions p = [10, 30, 5, 60] (matrix i is p[i] by p[i+1]). Find the minimum number of scalar…