Fewest range increments to build a target array
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Google. It tests arrays, greedy and difference array.
You start with an array of n zeros. In one move you choose a contiguous range [l, r] and add 1 to every element in it.
Given a non-negative integer array target of length n, implement:
-
min_moves(target: List[int]) -> int: the fewest moves that turn the zero array intotarget. - (Part 2)
optimal_moves(target: List[int]) -> List[Tuple[int, int]]: one list of inclusive ranges(l, r)of exactly that minimum length. Applying the ranges to the zero array must givetarget.
Constraints: 0 <= n <= 10^5 and 0 <= target[i] <= 10^9. For part 2, you may assume the answer is small enough to output.
Example 1
target = [2, 4, 1, 3]
min_moves -> 6
Two moves cover the whole prefix to height 2. Two more raise index 1 to 4. Index 2 needs only one of the earlier ranges to continue. Index 3 rises by 2 from 1, so it needs two new ranges. Total: 2 + 2 + 2 = 6.
Example 2
target = [3, 0, 3]
min_moves -> 6
The zero in the middle means no range can cross it, so each side needs its own 3 moves.
Clarifying questions
- Is the empty array 0 moves?
- In part 2, may ranges be listed in any order?
- Can the answer exceed 32 bits? (Up to about 10^14: yes, so use 64-bit or Python ints.)
What a strong answer covers
- Counts the rises: the answer is
target[0]plus the sum ofmax(0, target[i] - target[i-1]); each rise must start that many new ranges, and a drop can always end ranges, so the bound is reached. O(n). - Explains the argument with Example 2: the zero in the middle forces every range to end before it.
- Part 2: scans left to right with a stack of open range starts; on a rise, pushes that many starts at
i; on a drop, closes that many ranges ati - 1; closes the rest at the end. - Tests the examples, all zeros, a constant array (one height,
target[0]moves), and strictly increasing and decreasing arrays, checking part 2 by applying the ranges.
Follow-ups
- Each move can add 1 or subtract 1 from a range, starting from any array.
- Ranges have a maximum length.
- Answer the count after point updates to
target.
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.
