Gas Station
LeetCode 134 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ
Reset the start after any negative running tank.
நான் Gas Station (LeetCode 134) ஐ இப்படித் தீர்த்தேன் — Jump / Reachability பேட்டர்னின் ஒரு நடுத்தரம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.
கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.
Intuition
If total gas is less than total cost, no start works. Otherwise drive from a candidate start keeping a running tank; if the tank goes negative at i, no station between the start and i can work either, so restart from i + 1.
Approach
- 1
Total check → −1 if impossible.
- 2
Accumulate gas[i] − cost[i].
- 3
Negative → start = i + 1, tank = 0.
- 4
Return start.
நான் எப்படித் தீர்த்தேன்
Greedy single passPythonO(n) time · O(1) space
class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
if sum(cost)>sum(gas):
return -1
i=0
start=0
effort = 0
while i<len(gas):
effort += gas[i]-cost[i]
if effort<0:
effort=0
start=i+1
i+=1
return startGas Station — அடிக்கடி கேட்கப்படும் கேள்விகள்
Gas Station பின்னாலுள்ள intuition என்ன?
If total gas is less than total cost, no start works. Otherwise drive from a candidate start keeping a running tank; if the tank goes negative at i, no station between the start and i can work either, so restart from i + 1.
Gas Station (LeetCode 134) ஐ எப்படித் தீர்ப்பது?
1. Total check → −1 if impossible. 2. Accumulate gas[i] − cost[i]. 3. Negative → start = i + 1, tank = 0. 4. Return start.
Gas Station இன் time மற்றும் space complexity என்ன?
Time: O(n). Space: O(1). (Accepted approach: Greedy single pass.)
Gas Station இல் பொதுவான தவறுகள் என்ன?
The total check is what guarantees the found start completes the loop.