32 · Greedy Algorithms

#134 Gas Station

Mediumsolve on LeetCode ↗

frequently reported atFlipkartInfosysBloombergAmazonMicrosoftGoogle

the problem

In plain words

n stations sit on a circular road. Station i gives gas[i] fuel, and driving from station i to the next one costs cost[i]. Starting with an empty tank, return the start index that lets you drive the full circle once, or −1. If an answer exists, it is unique.

in gas = [1,2,3,4,5], cost = [3,4,5,1,2]

out 3

in gas = [2,3,4], cost = [3,4,3]

out -1

  • 1 ≤ n ≤ 10⁵
  • 0 ≤ gas[i], cost[i] ≤ 10⁴
  • The answer, if any, is unique

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #53
      Maximum Subarray
      Mediumin Arrays & Strings
    2. #55
      Jump Game
      Mediumin Greedy