Find the first circular tour that visits all Petrol Pumps

Pattern: Gas station

medium

If the total petrol is less than the total distance, no tour exists. Otherwise drive from pump 0 with a running tank; whenever it goes negative at pump i, no start from the current one up to i works, so start again at i + 1. The last start chosen is the answer.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

There are pumps on a circle. Pump i gives petrol[i] litres and the drive to the next pump uses distance[i]. Return the first pump from which a truck with an empty tank can drive the whole circle, or -1. The example gives 1.

The catalogue has no practice link; LeetCode's Gas Station is the same task.

Think first

  • When is a tour impossible from every start?
  • If you run dry at pump i starting from s, can any pump between s and i work?
  • So how many passes do you need?

Hints

    Brute force, and why it fails

    Try every start and drive the whole circle: O(n²).

    The key insight

    A failure at pump i rules out every start up to i at once, so one pass finds the only candidate, and a non-negative total guarantees it works.

    Dry run

    -20 
    11 
    42 
    -13 
    total2

    petrol [4, 6, 7, 4], distance [6, 5, 3, 5]. Gains -2, 1, 4, -1, total 2.

    Step 1 of 4

    The plan

    start = tank = total = 0
    for i: g = petrol[i] - distance[i]; total += g; tank += g
           if tank < 0: start = i + 1; tank = 0
    return -1 if total < 0 else start
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    One pass.

    Edge cases

    • One pump with enough petrol: 0.
    • Total exactly 0: the tour just works.
    • Every pump short: -1.
    I've built my logic, show the code

    Java

    class Solution {
        public int tour(int[] petrol, int[] distance) {
            int start = 0;
            long tank = 0, total = 0;
            for (int i = 0; i < petrol.length; i++) {
                long gain = petrol[i] - distance[i];
                total += gain;                      // over the whole loop: is there enough petrol at all?
                tank += gain;
                if (tank < 0) {                     // cannot reach i + 1 from start, nor from any pump in between
                    start = i + 1;
                    tank = 0;
                }
            }
            return total < 0 ? -1 : start;
        }
    }

    C++

    class Solution {
    public:
        int tour(vector<int>& petrol, vector<int>& distance) {
            int start = 0;
            long long tank = 0, total = 0;
            for (int i = 0; i < static_cast<int>(petrol.size()); i++) {
                long long gain = petrol[i] - distance[i];
                total += gain;                      // over the whole loop: is there enough petrol at all?
                tank += gain;
                if (tank < 0) {                     // cannot reach i + 1 from start, nor from any pump in between
                    start = i + 1;
                    tank = 0;
                }
            }
            return total < 0 ? -1 : start;
        }
    };

    Python

    class Solution:
        def tour(self, petrol: list[int], distance: list[int]) -> int:
            start = tank = total = 0
            for i, (p, d) in enumerate(zip(petrol, distance)):
                total += p - d                      # over the whole loop: is there enough petrol at all?
                tank += p - d
                if tank < 0:                        # cannot reach i + 1 from start, nor from any pump in between
                    start, tank = i + 1, 0
            return -1 if total < 0 else start

    Common mistakes

    • Forgetting the total check.
    • Restarting at i instead of i + 1.

    Similar problems