↓Skip to main content
  1. LeetCode/

LeetCode 134: Gas Station

·2 mins· ·
LeetCode Medium Array Greedy
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-11-11

  • Submissions: Accepted ×2

Approach
#

Two observations (Greedy):

  1. If sum(gas) < sum(cost), no full loop exists.
  2. If starting at s the tank first goes negative at i, no station between s and i can reach i + 1 either: arriving at it from s you had a non-negative tank, and starting there fresh only has less. So jump the start to i + 1 and reset the tank.

When the total suffices, the final start is the answer (unique by the problem’s guarantee).

My Attempts
#

Both submissions passed on the first try with this greedy.

Solution
#

class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        if sum(gas) < sum(cost):
            return -1
        start = tank = 0
        for i in range(len(gas)):
            tank += gas[i] - cost[i]
            if tank < 0:
                start, tank = i + 1, 0
        return start

Complexity
#

Time O(n), space O(1).

Mistakes to Avoid
#

  • Check the total first, or the final start might not complete the loop.
  • On a negative tank, jump the start to i + 1, not start + 1.

Interview Explanation
#

If total gas is below total cost there is no answer. Otherwise I accumulate gas minus cost, and whenever it goes negative no station since the current start can work, so I restart at the next station; the final start is the answer. Time O(n).

Related

LeetCode 11: Container With Most Water
·2 mins
LeetCode Medium Array Two-Pointers Greedy
LeetCode 11 note: start pointers at both ends and always move the shorter side; moving the taller side only narrows the width without raising the height
LeetCode 162: Find Peak Element
·2 mins
LeetCode Medium Array Binary-Search
LeetCode 162 note: nums[mid] < nums[mid + 1] guarantees a peak to the right (rising until the edge at worst), otherwise one at or left of mid
LeetCode 189: Rotate Array
·2 mins
LeetCode Medium Array Math Two-Pointers
LeetCode 189 note: take k %= n, then reverse three times: the whole array, the first k, and the last n - k, with O(1) extra space
LeetCode 204: Count Primes
·2 mins
LeetCode Medium Array Math Enumeration Number-Theory
LeetCode 204 note: the sieve of Eratosthenes, crossing out multiples of each prime p starting at p², with the outer loop only up to √n
LeetCode 106: Construct Binary Tree from Inorder and Postorder Traversal
·1 min
LeetCode Medium Array Hash-Table Divide-and-Conquer Tree
LeetCode 106 note: the last post-order value is the root; taking roots from the end of the post-order, build the right subtree before the left
LeetCode 137: Single Number II
·2 mins
LeetCode Medium Array Bit-Manipulation
LeetCode 137 note: with everything else appearing three times, count the 1s at each bit modulo 3; the leftover bits form the answer, minding negatives