AlgoMaster Logo

Gas Station

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

Intuition:

The Gas Station problem requires us to find a starting gas station, if it exists, from which we can complete a circular route. The brute force solution involves trying every gas station as a starting point and checking if a circular journey can be completed. This involves calculating the remaining gas from each station, updating the current gas as you proceed, and checking if you can reach back to the starting station.

Code:

2. Improved Efficient Solution

Intuition:

The improved solution takes advantage of certain observations:

  1. If the total gas is greater than the total cost, then a solution must exist.
  2. If at any station, the current gas becomes negative, it indicates this station cannot be a starting point, and all stations before it are also not viable.

We traverse through each station once, keeping track of the total surplus and current surplus. Whenever the current surplus becomes negative, we reset the potential start point to the next station.

Code: