Intermediate Level

Implement the gasStationCircuitStart method that returns the gas station index from which the full circuit can be completed.

The input contains two arrays: gas and cost. At each station, gas[i] is the fuel available and cost[i] is the fuel needed to travel to the next station.

Your task is to return the starting station index from where the full circular route can be completed. If no such start exists, return -1.

For example, with gas = [1,2,3,4,5] and cost = [3,4,5,1,2], starting from index 3 allows completing the circuit.

Example 1

Input
gas (int[]) = [1,2,3,4,5]
cost (int[]) = [3,4,5,1,2]
size (int) = 5
Returns (int) 3

Example 2

Input
gas (int[]) = [2,3,4]
cost (int[]) = [3,4,3]
size (int) = 3
Returns (int) -1

Example 3

Input
gas (int[]) = [5]
cost (int[]) = [4]
size (int) = 1
Returns (int) 0

First, the total gas must be at least the total cost. If not, completing the route is impossible.

Then scan the stations while tracking the current tank balance. If the tank becomes negative at station i, no station from the current start up to i can be a valid start. Reset the start to i + 1 and start counting tank balance again.

After the scan, the stored start index is the valid answer.

Pseudocode:

function gasStationCircuitStart(gas, cost, size):
    total = 0
    tank = 0
    start = 0
    for i from 0 to size - 1:
        balance = gas[i] - cost[i]
        total = total + balance
        tank = tank + balance
        if tank < 0:
            start = i + 1
            tank = 0
    if total < 0:
        return -1
    return start
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.