




Sponsored
Sponsored
This approach leverages the greedy paradigm. The main idea is to iterate over the stations while keeping track of the total gas and total cost. Additionally, we maintain a running sum (which is the cumulative balance of gas at each station) and a start index. If the running sum ever becomes negative, it implies that the current segment of the journey is infeasible. Thus, we reset the running sum and choose the next station as the candidate for the starting point. Finally, if the total gas is greater than or equal to the total cost, the last chosen candidate is the valid starting point.
Time Complexity: O(n), where n is the number of stations.
Space Complexity: O(1), as extra space used is constant.
1def canCompleteCircuit(gas, cost):
2    totalGas, totalCost = 0, 0
3    start, currentGas = 0, 0
4
5    for i in range(len(gas)):
6        totalGas += gas[i]
7        totalCost += cost[i]
8        currentGas += gas[i] - cost[i]
9
10        if currentGas < 0:
11            start = i + 1
12            currentGas = 0
13
14    return start if totalGas >= totalCost else -1
15
16
17gas = [1, 2, 3, 4, 5]
18cost = [3, 4, 5, 1, 2]
19print(canCompleteCircuit(gas, cost))
20In Python, the function iterates through the gas stations and calculates both the total gas and the total cost. The variable currentGas keeps track of the difference between gas and cost. Reset the start index whenever this balance turns negative. If the total gas is sufficient to meet all costs, the function returns the most recently identified start; otherwise, it returns -1.
This approach attempts to simulate the journey starting from each station. For each potential start, check if the car can complete the circuit using the available gas at each station. While this approach may be easier to understand, it is inefficient because it checks each station iteratively, leading to potentially high computational costs for longer arrays. It is not recommended for larger datasets but can be useful for understanding how the journey works preliminarily.
Time Complexity: O(n^2) due to double iteration.
Space Complexity: O(1) as no extra space is utilized.
1
In Java, the brute force solution is similarly executed by checking every gas station as possible starting points. The journey is processed for each start index by accumulating the individual gas difference, stopping early when the tank gas isn't sufficient.