Data Structures & AlgorithmsVery hardProduct company OA

Circular route: station i gives gas[i] and driving to station i + 1 costs cost[i], with gas = [3, 1, 5, 2, 6] and cost = [4, 3, 2, 4, 2]. The greedy scan resets the start to i + 1 whenever the running tank goes negative. Which start index is returned (or −1 if no full loop is possible)?

  1. A. 3
  2. B. −1
  3. C. 0
  4. D. 2

Correct answer: D. 2

Total gas 17 ≥ total cost 15, so a solution exists. Net gains: −1, −2, 3, −2, 4. From 0: −1 < 0 → restart at 1; −2 < 0 → restart at 2; 3, 1, 5 stays ≥ 0 → start 2. Checking the wrap: 5 + (−1) + (−2) = 2 ≥ 0. Starting at 3 fails at once (2 − 4 < 0) and 0 fails immediately (3 − 4 < 0). Index 4 would also complete the loop, but the greedy returns the first start after the last reset, 2.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic