#134
Gas Station
MediumArrayGreedyGreedyArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach uses a greedy method to determine if a complete circuit can be made. By tracking the total gas and cost, we can identify the starting point in a single pass.
⚙️
Algorithm
4 steps- 1Step 1: Initialize total gas and total cost, and a temporary tank variable.
- 2Step 2: Loop through each gas station, updating the total gas and cost, and the temporary tank.
- 3Step 3: If the temporary tank drops below zero, reset the starting point to the next station and reset the temporary tank.
- 4Step 4: After the loop, if total gas is greater than or equal to total cost, return the starting index; otherwise return -1.
solution.py13 lines
1# Full working Python code
2
3def canCompleteCircuit(gas, cost):
4 total_gas = total_cost = tank = start = 0
5 n = len(gas)
6 for i in range(n):
7 total_gas += gas[i]
8 total_cost += cost[i]
9 tank += gas[i] - cost[i]
10 if tank < 0:
11 start = i + 1
12 tank = 0
13 return start if total_gas >= total_cost else -1ℹ
Complexity note: This approach only requires a single pass through the gas stations, leading to O(n) time complexity and O(1) space complexity as we only use a few variables.
- 1The total gas must be greater than or equal to the total cost to complete the circuit.
- 2If the tank goes negative, the next station must be the new starting point.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.