← Questions

Fewest range increments to build a target array

0
GoogleCoding

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 into target.
  • (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 give target.

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 of max(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 at i - 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

arrays · greedy · difference array

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding