Problem Description
Given two integer arrays gas and cost representing gas stations in a circular route, determine the starting index from which a car (with an unlimited tank but starting empty) can complete the circuit once in a clockwise direction. At each station i, gas[i] is the amount of gas available and cost[i] is the gas required to travel to the next station. If it is not possible to make a complete circuit, return -1.
Key Insights
- If the total amount of gas available is less than the total travel cost, then completing the circuit is impossible.
- A greedy approach can be used by keeping track of the current surplus of gas. If the surplus becomes negative at any station, the journey cannot start from any station before that point.
- Restart the journey from the next station whenever the surplus goes negative.
- The problem guarantees that if a solution exists, it is unique.
Space and Time Complexity
Time Complexity: O(n), where n is the number of gas stations, as we traverse the list only once. Space Complexity: O(1), as no extra space is used other than a few variables.
Solution
The solution involves iterating over the list of stations while maintaining two variables: one for the current gas surplus and one for the total gas surplus. If at any station the current surplus drops below zero, the current starting station is not viable and we set the starting station to the next index and reset the current surplus. After one pass, if the total gas surplus is non-negative, then the identified station is the valid starting point.