Find the Unique Start for a Circular Fuel Circuit

Quick Overview

Find the unique feasible circular gas-route start by discarding failed segments and checking total net supply.

Find the Unique Start for a Circular Fuel Circuit

Company: Amazon

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

### Problem Along a clockwise circular route, station `i` supplies `gas[i]` units and traveling to the next station costs `cost[i]`. Choose a zero-based starting station, begin with an empty unlimited-capacity tank, and collect gas whenever visiting a station. Return the starting index if a full circuit is possible, otherwise -1. If a valid start exists, it is guaranteed to be unique. ```cpp int canCompleteCircuit(vector<int>& gas, vector<int>& cost); ``` ### Examples ```text Input: gas = [2,0,4], cost = [3,1,2] Output: 2 ``` Starting at 2 leaves successive post-travel balances 2,1,0. ```text Input: gas = [1,2], cost = [2,2] Output: -1 ``` ### Constraints - Both arrays have the same length, between 1 and 100000. - Each amount and cost is between 0 and 10000, inclusive. - A feasible starting index, when present, is unique.

Overview: Find the unique feasible circular gas-route start by discarding failed segments and checking total net supply.

Amazon logo
Amazon
Date not reported
mediumSoftware EngineerOtherCoding & Algorithms
0
0

Problem

Along a clockwise circular route, station i supplies gas[i] units and traveling to the next station costs cost[i]. Choose a zero-based starting station, begin with an empty unlimited-capacity tank, and collect gas whenever visiting a station. Return the starting index if a full circuit is possible, otherwise -1. If a valid start exists, it is guaranteed to be unique.

int canCompleteCircuit(vector<int>& gas, vector<int>& cost);

Examples

Input: gas = [2,0,4], cost = [3,1,2]
Output: 2

Starting at 2 leaves successive post-travel balances 2,1,0.

Input: gas = [1,2], cost = [2,2]
Output: -1

Constraints

  • Both arrays have the same length, between 1 and 100000.
  • Each amount and cost is between 0 and 10000, inclusive.
  • A feasible starting index, when present, is unique.