1. Brute Force — Simulate Each Starting Station
Intuition
Try starting at every station i from 0 to N - 1. Maintain tank. Move to (j + 1) % N. If tank ever becomes negative, break and try next station. If we complete N steps, return i. If no station works, return -1.
When to apply: When N <= 500.
Algorithm
- Step 1: Loop start from 0 to N - 1.
- Step 2: Set tank = 0, steps = 0, j = start.
- Step 3: While steps < N: tank += gas[j] - cost[j]. If tank < 0 break. Advance j = (j + 1) % N, steps++.
- Step 4: If steps == N, return start.
- Step 5: Return -1.
#include <iostream>#include <vector> using namespace std; class Solution {public: int canCompleteCircuit(vector<int>& gas, vector<int>& cost) { int n = gas.size(); for (int start = 0; start < n; ++start) { int tank = 0; int steps = 0; int j = start; while (steps < n) { tank += gas[j] - cost[j]; if (tank < 0) break; j = (j + 1) % n; steps++; } if (steps == n) return start; } return -1; }}; int main() { Solution sol; vector<int> gas = {1, 2, 3, 4, 5}; vector<int> cost = {3, 4, 5, 1, 2}; cout << "Start station: " << sol.canCompleteCircuit(gas, cost) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— N candidate starts, each potentially simulating N steps. - Space complexity:
O(1)— Scalar integer variables only.
Why Brute Force Doesn't Scale:
With N = 105, N2 is 1010 operations, which severely times out. The greedy single pass runs in ~10ms.
For N = 100,000: O(N) requires exactly 100,000 iterations, finishing in ~5ms.