Gas Station Circuit
Given gas stations arranged in a circle with gas[i] fuel available at station i and cost[i] fuel needed to travel to next station, find the starting station to complete the circuit. If total gas >= total cost, exactly one solution exists. The greedy algorithm finds it in O(n) single pass by tracking when the tank goes negative and resetting the start position.
Visualization
Interactive visualization for Gas Station Circuit
Interactive visualization with step-by-step execution
Implementation
1function canCompleteCircuit(gas: number[], cost: number[]): number {
2 let totalGas = 0, totalCost = 0, tank = 0, start = 0;
3
4 for (let i = 0; i < gas.length; i++) {
5 totalGas += gas[i];
6 totalCost += cost[i];
7 tank += gas[i] - cost[i];
8
9 if (tank < 0) {
10 start = i + 1;
11 tank = 0;
12 }
13 }
14
15 return totalGas >= totalCost ? start : -1;
16}Deep Dive
Theoretical Foundation
Gas Station leverages two insights: (1) If sum(gas) >= sum(cost), a solution exists and is unique. (2) If starting at i fails at position j (tank becomes negative), then any starting position between i and j will also fail. Proof: if starting at i fails at j, starting at k (i < k < j) has less accumulated gas, so also fails at or before j. Greedy algorithm: track running tank. When tank < 0, reset start to next position and tank to 0. If total gas >= total cost, return start; else return -1. Time: O(n) single pass.
Complexity
Time
O(n)
O(n)
O(n)
Space
O(1)
Applications
Industry Use
Route planning for fuel efficiency
Circular tour problems
Resource distribution optimization
Supply chain logistics
Delivery route optimization
Use Cases
Related Algorithms
Huffman Coding
Huffman Coding is a lossless data compression algorithm that creates optimal prefix-free variable-length codes based on character frequencies. Developed by David A. Huffman in 1952 as a student at MIT, it uses a greedy approach to build a binary tree where frequent characters get shorter codes. This algorithm is fundamental in ZIP, JPEG, MP3, and many compression formats.
Activity Selection Problem
Select the maximum number of non-overlapping activities from a set, where each activity has a start and end time. This classic greedy algorithm demonstrates the greedy choice property: always selecting the activity that finishes earliest leaves the most room for remaining activities. Used in scheduling problems, resource allocation, and interval management. Achieves optimal solution with O(n log n) time complexity.
Fractional Knapsack Problem
Given items with values and weights, and a knapsack with capacity, select items (or fractions thereof) to maximize total value. Unlike the 0/1 knapsack where items must be taken whole, the fractional knapsack allows taking fractions of items. The greedy approach of taking items in order of value-to-weight ratio yields the optimal solution in O(n log n) time. This demonstrates when greedy algorithms work vs. when dynamic programming is needed.
Job Sequencing with Deadlines
Schedule jobs with deadlines and profits to maximize total profit. Each job takes 1 unit time and has a deadline and profit. The greedy strategy is to sort jobs by profit (descending) and greedily schedule each job as late as possible before its deadline. This maximizes profit while respecting constraints. Used in task scheduling, CPU job management, and project planning.