Data Structures & AlgorithmsModerateProduct company OA · Amazon/Microsoft-style OA
What does this program print?
What does this program print?
a = [6, 3, 8, 1]
mx = [0] * len(a)
mx[-1] = a[-1]
for i in range(len(a) - 2, -1, -1):
mx[i] = max(a[i], mx[i + 1])
print(mx)- A. [6, 3, 8, 1]
- B. [8, 3, 8, 1]
- C. [8, 8, 8, 1]
- D. [8, 8, 1, 1]
Correct answer: C. [8, 8, 8, 1]
The loop builds suffix maxima from right to left: each entry is the larger of the element and the maximum after it, so the output is the suffix-maximum array of the input.
More Coding Interview Problems questions
- Array a = [7, -3, 2, 5, -8, 4, 1, -1]. How many contiguous subarrays have a sum divisible by 3? (Zero is divisible by 3.)
- Sorted list [3, 6, 9, 12, 15, 18, 21]. How many index triples i < j < k satisfy vals[i] + vals[j] = vals[k]?
- How many contiguous subarrays of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] sum to exactly 15?
- Array a = [9, 4, 7, 1, 8, 2, 6, 3]. How many index pairs i < j have |a[i] - a[j]| >= 5?
- Among [5, 3, 6, 12, 9, 10, 1], choose two different elements. What is the largest possible value of x OR y?
- How many pairs of distinct elements of [1, 4, 6, 7, 10, 13, 15] have a sum that is a perfect square (1, 4, 9, 16, ...)?