Fewest decrements to make an array a 1-to-k-to-1 pyramid
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Amazon. It tests arrays, greedy and prefix scan.
You are given an array arr of n non-negative integers. One operation picks any index and lowers that element by exactly 1. Elements can never be raised.
Return the minimum number of operations needed to turn arr into a pyramid array:
- it may start and/or end with any number of zeros, and
- the remaining (non-zero) part reads
1, 2, 3, ..., k, ..., 3, 2, 1for some peakk >= 1: it climbs by exactly 1 to a single peak, then falls by exactly 1 back to 1.
An array of all zeros counts as a pyramid (its non-zero part is empty).
Implement:
def min_ops_to_bitonic(arr: list[int]) -> int: ...
Constraints: 1 <= n <= 10^5, 0 <= arr[i] <= 10^9. Aim for better than O(n²).
Example 1
arr = [2, 5, 4, 6, 2]
output: 10
Lower it to [1, 2, 3, 2, 1]. The array sums to 19, the pyramid to 9, so 10 decrements.
Example 2
arr = [4, 4, 4, 4]
output: 12
No height-3 pyramid fits in 4 slots (it needs 5). The best is a height-2 pyramid such as [1, 2, 1, 0], sum 4, so 16 - 4 = 12.
Clarifying questions
- Can there be zeros between the pyramid's parts? (No: the non-zero part is contiguous.)
- Must the pyramid have a single peak, with no flat top?
- Is an array of all zeros already done, with cost
0? - Can the sum overflow 32 bits? (Yes, up to about
10^14.)
What a strong answer covers
- Sees that every element outside the pyramid goes to 0, so the cost is
sum(arr) - h^2for a pyramid of heighth. The task is to find the tallest pyramid that fits. - Computes, in one left-to-right pass, how tall a left slope can rise to each index, capped by
arr[i]and by "one more than the previous". It does the same from the right. - The tallest peak at an index is the smaller of the two, so the best
his the largest such value. That is O(n) time. - Explains why the edges of the array cap the height (a peak of
hneedsh - 1cells on each side). - Tests both examples, all zeros, a single element, a zero in the middle, and very large values.
Follow-ups
- Return the final array.
- Allow increases too, each at cost 1.
- The peak must be at a given index.
- Allow a flat top of any width.
Where it's asked
What it tests
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
