Limited Time Offer:Up to 20% off Hello Interview Premium
Up to 20% off Hello Interview Premium 🎉
Hello Interview
Learn Code
Introduction
Overview
Container With Most Water
Two Sum (Sorted Array)
3-Sum
Triangle Numbers
Move Zeroes
Sort Colors
Trapping Rain Water
Overview
Maximum Sum of Subarrays of Size K
Max Points You Can Obtain From Cards
Max Sum of Distinct Subarrays Length k
Overview
Longest Substring Without Repeating Characters
Longest Repeating Character Replacement
Overview
Can Attend Meetings
Insert Interval
Non-Overlapping Intervals
Merge Intervals
Employee Free Time
Overview
Valid Parentheses
Decode String
Longest Valid Parentheses
Monotonic Stack
Daily Temperatures
Largest Rectangle in Histogram
Overview
Linked List Cycle
Palindrome Linked List
Remove Nth Node From End of List
Reorder List
Swap Nodes in Pairs
Overview
Apple Harvest (Koko Eating Bananas)
Search in Rotated Sorted Array
Split Array Largest Sum
Kth Smallest Element in a Sorted Matrix
Minimum Shipping Capacity
Overview
Kth Largest Element in an Array
K Closest Points to Origin
Find K Closest Elements
Merge K Sorted Lists
Median from Data Stream
Introduction
Fundamentals
Return Values
Maximum Depth of Binary Tree
Path Sum
Passing Values Down and Helper Functions
Validate Binary Search Tree
Calculate Tilt
Diameter of a Binary Tree
Path Sum II
Longest Univalue Path
Graphs Overview
Adjacency List
Copy Graph
Graph Valid Tree
Matrices
Flood Fill
Number of Islands
Surrounded Regions
Pacific Atlantic Water Flow
Introduction
Overview
Level Order Sum
Rightmost Node
Zigzag Level Order
Maximum Width of Binary Tree
Graphs Overview
Minimum Knight Moves
Rotting Oranges
01-Matrix
Bus Routes
Overview
Word Search
Solution Space Trees
Subsets
Generate Parentheses
Combination Sum
Palindrome Partitioning
N-Queens
Overview
Course Schedule
Course Schedule II
Shortest Path Algorithms
Network Delay Time
Cheapest Flights Within K Stops
Path With Minimum Effort
Find City with Fewest Reachable
Fundamentals
Solving a Question with Dynamic Programming
Counting Bits
Decode Ways
Unique Paths
Maximal Square
Longest Increasing Subsequence
Word Break
Maximum Profit in Job Scheduling
Paint House
Paint House II
Minimum Window Subsequence
Overview
Best Time to Buy and Sell Stock
Gas Station
Jump Game
Jump Game II
Partition Labels
Overview
Implement Trie Methods
Prefix Matching
Overview
Count Vowels in Substrings
Subarray Sum Equals K
Spiral Matrix
Rotate Image
Set Matrix Zeroes
Vote For New Content
Pricing
Sign in / Sign up
Search
⌘K
Pricing

Tutor

Greedy Algorithms

Gas Station

medium

max (21)341224132;341225102;21365487109
Count: 10
abcValid triangle requires:a + b > c AND a + c > b AND b + c > a(every pair must sum to more than the third side)3511SOURCE23211SOURCE23UNREACHABLE$100$100$100$5000SRC123DST$100$100$1000SRC123DST01233141Threshold: 4Answer: 32 reachable01234231118Threshold: 2Answer: 01 reachable1102233321432263321
DESCRIPTION (inspired by Leetcode.com)

There are n gas stations along a circular route. You are given two integer arrays gas and cost of length n. At each gas station i, gas[i] represents the amount of gas you receive by stopping at this station, and cost[i] represents the amount of gas required to travel from station i to the next station. You begin the journey with an empty tank at one of the gas stations.

Write a function to return the starting gas station's index if you can travel around the circuit once in the clockwise direction; otherwise, return -1. Note that if there exists a solution, it is guaranteed to be unique. Also, you can only travel from station i to station i + 1, and the last station will lead back to the first station.

Input:

gas = [5,2,0,3,3]
cost = [1,5,5,1,1]

Output:

3

Explanation:

Start at station 3 and fill up with 3 units of gas. Your tank = 0 + 3 = 3 Travel to station 4 with 1 unit of gas, and fill up with 3 units of gas. Your tank = 3 - 1 + 3 = 5 Travel to station 0 with 1 unit of gas, and fill up with 5 units of gas. Your tank = 5 - 1 + 5 = 9 Travel to station 1 with 1 unit of gas, and fill up with 2 units of gas. Your tank = 9 - 1 + 2 = 10 Travel to station 2 with 5 units of gas, and fill up with 0 units of gas. Your tank = 10 - 5 + 0 = 5 Travel back to station 3 with 5 units of gas to complete the circuit. Therefore, return 3 as the starting index.

Solution

Visualization
Python
Language
Try these examples:
def canCompleteCircuit(gas, cost):
if sum(gas) < sum(cost):
return -1
start, fuel = 0, 0
for i in range(len(gas)):
if fuel + gas[i] - cost[i] < 0:
# can't reach next station:
# try starting from next station
start, fuel = i + 1, 0
else:
# can reach next station:
# update remaining fuel
fuel += gas[i] - cost[i]
return start
5203315511

gas station

0 / 12

Explanation

If there is more gas along the route than the cost of the route, then there is guaranteed to be a solution to the problem. So the first step is to check if the sum of the gas is greater than or equal to the sum of the cost. If it is not, then we return -1.
Next, we iterate through the gas station to find the starting index of our circuit using a greedy approach: whenever we don't have enough gas to reach the next station, we move our starting gas station to the next station and reset our gas tank.

Walkthrough

We start at the first station, and fill our tank with gas[0] = 5 units of gas. From there, it takes cost[0] = 1 units of gas to travel to the next station, so we arrive at station 2 (index 1) with 4 units of gas.
Visualization
Python
Language
def canCompleteCircuit(gas, cost):
if sum(gas) < sum(cost):
return -1
start, fuel = 0, 0
for i in range(len(gas)):
if fuel + gas[i] - cost[i] < 0:
# can't reach next station:
# try starting from next station
start, fuel = i + 1, 0
else:
# can reach next station:
# update remaining fuel
fuel += gas[i] - cost[i]
return start
52033start = 0i = 015511fuel0

i = 0

0 / 2

Traveling between stations 1 (`i = 0`) and 2 (`i = 1`)
At station 2, we fill our tank with gas[1] = 2 units of gas, for a total of 6 units of gas. It takes cost[1] = 5 units of gas to travel to the next station, so we arrive at station 3 with 1 unit of gas.
Visualization
Python
Language
def canCompleteCircuit(gas, cost):
if sum(gas) < sum(cost):
return -1
start, fuel = 0, 0
for i in range(len(gas)):
if fuel + gas[i] - cost[i] < 0:
# can't reach next station:
# try starting from next station
start, fuel = i + 1, 0
else:
# can reach next station:
# update remaining fuel
fuel += gas[i] - cost[i]
return start
52033start = 0i = 115511fuel4

i = 1

0 / 2

Traveling between stations 2 (`i = 1`) and 3 (`i = 2`)

Greedy Approach

Now at station 3, we fill our tank with gas[2] = 0 units of gas, for a total of 1 unit of gas. It takes cost[2] = 5 units of gas to travel to the next station, which we don't have.
This is where our greedy approach comes in. We reset our starting station to the next station i + 1 and reset our gas tank to 0. We can do this because all other start indexes between 0 and 2 will also run into the same problem of not having enough gas to reach the next station, so we can rule them out.
Visualization
Python
Language
def canCompleteCircuit(gas, cost):
if sum(gas) < sum(cost):
return -1
start, fuel = 0, 0
for i in range(len(gas)):
if fuel + gas[i] - cost[i] < 0:
# can't reach next station:
# try starting from next station
start, fuel = i + 1, 0
else:
# can reach next station:
# update remaining fuel
fuel += gas[i] - cost[i]
return start
52033start = 0i = 215511fuel1

i = 2

0 / 2

Resetting the start index
If we follow this approach of resetting the start index and gas tank whenever we don't have enough gas to reach the next station, then when we finish iterating, the last start index will be the solution to the problem.
Visualization
Python
Language
def canCompleteCircuit(gas, cost):
if sum(gas) < sum(cost):
return -1
start, fuel = 0, 0
for i in range(len(gas)):
if fuel + gas[i] - cost[i] < 0:
# can't reach next station:
# try starting from next station
start, fuel = i + 1, 0
else:
# can reach next station:
# update remaining fuel
fuel += gas[i] - cost[i]
return start
52033start = 3i = 315511fuel2

update fuel

0 / 3

Test Your Knowledge

Login to take the complexity quiz and track your progress

Complexity Analysis

Time Complexity: O(n) where n is the number of gas stations. We only iterate through the gas stations once.

Space Complexity: O(1) We only use constant extra space for variables.

Mark as read

Next: Jump Game

Your account is free and you can post anonymously if you choose.

Unlock Premium Coding Content

Interactive algorithm visualizations
Guided Practice
Recent interview questions
Learn More
Reading Progress

On This Page

Solution

Explanation

Walkthrough

Questions
Meta SWE Interview QuestionsAmazon SWE Interview QuestionsGoogle SWE Interview QuestionsOpenAI SWE Interview QuestionsEngineering Manager (EM) Interview Questions
Learn
Learn System DesignLearn DSALearn BehavioralLearn ML System DesignLearn Low Level DesignGuided Practice
Links
FAQPricingGift PremiumHello Interview Premium
Legal
Terms and ConditionsPrivacy PolicySecurity
Contact
About UsProduct Support

7511 Greenwood Ave North Unit #4238 Seattle WA 98103


© 2026 Optick Labs Inc. All rights reserved.

Login to track your progress