KatInterview

Greedy Starting Point for a Circular Fuel Route

Greedy & IntervalsAuto-graded · 20 test cases
MediumAuto-gradedGreedy & Intervalsgreedyarraystwo-pointers

Last updated

Tests whether a candidate can apply a greedy one-pass argument to find the unique valid departure station in a circular gas-station problem.

Problem

You are planning a road trip along a circular route with n stops numbered 0 through n - 1. At each stop i you can pick up gas[i] litres of fuel. Driving from stop i to the next stop (i + 1) % n burns exactly cost[i] litres.

Your tank starts empty when you depart. You may choose any stop as your departure point. Find the index of the only stop from which you can complete the full loop without your fuel tank ever going negative. If no such stop exists, return -1.

You are guaranteed that if a solution exists, it is unique.

Rules

  • You travel clockwise only: from stop i you always proceed to stop (i + 1) % n.
  • Before leaving a stop you fill up with that stop's fuel, then spend fuel driving to the next stop.
  • Your tank may reach exactly 0 — that is still valid.
  • The answer is unique when it exists.

Constraints

  • 1 <= n <= 10^5
  • 0 <= gas[i], cost[i] <= 10^4
  • gas and cost have the same length n.

Examples

Example 1

Input: find_departure_stop([1, 2, 3, 4, 5], [3, 4, 5, 1, 2])

Output: 3

Example 2

Input: find_departure_stop([2, 3, 4], [3, 4, 3])

Output: -1

Example 3

Input: find_departure_stop([5], [5])

Output: 0

Hints

Hint 1

Compute the net gain or loss at each stop. If the total across all stops is negative, no starting point can work — return -1 immediately.

Hint 2

Simulate a journey from a candidate start, keeping a running tank balance. If the balance ever goes negative, can any stop between your candidate and the current stop be a better starting point? Think about why not.

Hint 3

Once you understand why a negative balance forces you to abandon every stop up to and including the current one, the rest of the algorithm writes itself in a single loop with O(1) extra space.