Skip to the solution
MediumDSA12 min read

How do you solve the Gas Station problem?

380 views

The problem

Question presented to candidate: "There are n petrol stations on a circular road. Station i has gas[i] units of fuel, and driving from station i to the next one costs cost[i]. Your car starts empty with an unlimited tank. Write a Python function that returns the index of the station to start from to drive around the circle once, or -1 if that is impossible."

What a strong answer should cover:

  • Reduce each station to its net gain gas[i] - cost[i].
  • Fact 1: if the total gain is negative, no start works; otherwise one does.
  • Fact 2: if the tank goes negative after station j, no station from the current start to j can be a start, so jump to j + 1 and reset the tank.
  • The one-pass solution with total, tank and start: O(n) time, O(1) space โ€” and the prefix-sum argument for why the final start works.
  • The O(nยฒ) brute force as a baseline, and the % n wrap-around it needs.
  • Python details: zip(gas, cost) or range(len(gas)), integers that cannot overflow, and that the answer is a station index (not a fuel amount).

Clarifying questions expected:

  • Does the tank start empty, with no capacity limit?
  • Is the answer guaranteed to be unique, and what should be returned when there is none?

Code / implementation expected: Yes โ€” can_complete_circuit(gas, cost) in Python 3, one pass.

  • dsa
  • greedy
  • arrays

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read ยท 11 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonOne-pass greedy on 7 inputs
PythonTank trace, 3,000 random cases vs brute force and prefix-min, and work counts

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 95 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

Trapping Rain Water with two pointers โ€” why does leftMax/rightMax work in O(1) space?

Continue