Leetcode 134: Gas Station

grid47
grid47
Exploring patterns and algorithms
Oct 24, 2024 6 min read

A calm sequence of gas stations, each glowing softly, with the optimal starting point gently illuminated.
Solution to LeetCode 134: Gas Station Problem

You are given ’n’ gas stations along a circular route, where each station has a certain amount of gas and a cost associated with traveling to the next station. The goal is to find the starting station from where you can complete a full circle. If no such starting station exists, return -1.
Problem
Approach
Steps
Complexity
Input: You are given two integer arrays, gas and cost, where gas[i] represents the gas available at the ith station and cost[i] represents the cost of gas to travel from the ith station to the next.
Example: gas = [1,2,3,4,5], cost = [3,4,5,1,2]
Constraints:
• n == gas.length == cost.length
• 1 <= n <= 10^5
• 0 <= gas[i], cost[i] <= 10^4
Output: Return the index of the station where the journey can be completed successfully. If no such index exists, return -1.
Example: Output: 3
Constraints:
• The output should be -1 if no valid starting station is found.
Goal: To find the starting station index where the gas in the car is enough to travel around the circuit.
Steps:
• 1. First, check if the total gas is greater than or equal to the total cost. If not, return -1.
• 2. Traverse through the stations and simulate the journey. If the gas in the tank goes negative, reset the tank and set the next station as the potential starting station.
• 3. If you complete the journey, return the index of the starting station.
Goal: The constraints ensure that the problem can be solved efficiently even for large inputs.
Steps:
• 1 <= n <= 10^5
• 0 <= gas[i], cost[i] <= 10^4
Assumptions:
• It is guaranteed that if a solution exists, it will be unique.
Input: gas = [1,2,3,4,5], cost = [3,4,5,1,2]
Explanation: In this case, you start at station 3. Traveling from station 3, you will be able to make the full journey and return to station 3.

Input: gas = [2,3,4], cost = [3,4,3]
Explanation: In this case, there is no starting station from where the journey can be completed successfully.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus