VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-a-tour-that-visits-all-stations/

⇱ Gas Station - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Gas Station

Last Updated : 6 Sep, 2025

Given two arrays gas[] and cost[], each gas station i provides gas[i] fuel, and it takes cost[i] fuel to travel to the next station. Starting with an empty tank, find the index of the gas station from which you can complete a full circular tour. If it’s not possible, return -1.

Note: If a solution exists, it is guaranteed to be unique.

Examples:

Input: gas[] = [4, 5, 7, 4], cost[] = [6, 6, 3, 5]
Output: 2
Explanation: Start at gas station at index 2 and fill up with 7 units of gas. Your tank = 0 + 7 = 7
Travel to station 3. Available gas = (7 - 3 + 4) = 8.
Travel to station 0. Available gas = (8 - 5 + 4) = 7.
Travel to station 1. Available gas = (7 - 6 + 5) = 6.
Return to station 2. Available gas = (6 - 6) = 0.
Therefore, 2 is the starting index.

Input: gas[] = [3, 9], cost[] = [7, 6]
Output: -1
Explanation: There is no gas station to start with such that you can complete the tour.

[Naive Approach] Considering Every Index as Starting Point - O(n2) Time and O(1) Space

The simplest approach is to consider each index as a starting point and check if a car can complete the circular tour starting from that index. If we find a valid starting point, we will return it.


Output
2

[Expected Approach 1] Greedy Approach - O(n) Time and O(1) Space

The idea is maintain the available gas while traversing. If it ever drops below zero at station i, the journey cannot start from the current starting point, so we shift the starting point to i + 1.

How it Works?

  • At each station i, update available gas as: available gas + gas[i] - cost[i].
  • If available gas < 0 reset starting point to i + 1 and continue.
  • After completing the traversal, check if the chosen starting point can cover the circular tour.

Note: If starting from index s fails at station i (available gas < 0), then no station between s and i can be a valid start either because each of them would reach station i with even less gas than starting at s. Therefore, the next possible candidate is i + 1.


Output
2

[Expected Approach 2] Greedy Approach in One Pass - O(n) Time and O(1) Space

This approach is an optimization of the previous one. After completing a full traversal of the array, instead of checking validity by circularly traversing from the starting index, we calculate the total remaining gas (the net difference between gas and cost). If this difference is greater than or equal to zero, the starting point is valid; otherwise, completing a circular loop is not possible.



Output
2
Comment