1282. Every Viable Start

A delivery van drives around a ring road with n depots numbered 0 to n - 1. At depot i it first collects fuel[i] units of fuel, then burns cost[i] units to drive to depot (i + 1) mod n. The van begins at some depot with an empty tank and completes exactly one lap of n legs, ending where it began. A start depot is viable when the tank level is never negative after paying for any of the n legs.

Return every viable start depot as an array in ascending order, or an empty array if there is none. The arrays fuel and cost have the same length n. Aim for O(n) time, for instance with prefix sums over the doubled ring and a sliding-window minimum.

Example 1

Input:
fuel = [3,1,2], cost = [2,2,1]
Output:
[0,2]
Explanation:

Starting at station 0 or station 2 the tank never goes below zero, but starting at station 1 the first leg leaves -1, so the answer is [0, 2].

Example 2

Input:
fuel = [1,1], cost = [2,2]
Output:
[]
Explanation:

Every leg burns one unit more than it gains, so no start survives and the result is empty.

Example 3

Input:
fuel = [5], cost = [5]
Output:
[0]
Explanation:

A single station gains 5 and spends 5, ending at exactly zero, so station 0 is viable.

Constraints

  • 1 ≤ n ≤ 105
  • fuel.length == cost.length == n
  • 0 ≤ fuel[i], cost[i] ≤ 104

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…