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)?
- A. 3
- B. −1
- C. 0
- 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.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- A monotonic stack removes duplicate letters so that each letter appears exactly once and the result is the lexicographically SMALLEST…
- 20 keys are hashed independently and uniformly into 100 slots. What is the EXPECTED number of colliding pairs (unordered pairs of keys…
- How many contiguous subarrays of [1, 3, 2, 4, 6, 5] satisfy max − min ≤ 2? (Two monotonic deques shrink the window from the left.)
- What is the smallest positive integer missing from [3, 4, −1, 1, 7, 2, 2, 9]? (In-place cyclic placement: put each value v with 1 ≤ v ≤ n…
- Which problem CANNOT be solved by a plain variable-size sliding window that shrinks from the left?
- The Boyer–Moore majority vote (candidate/counter, no verification pass) runs on [3, 5, 5, 7, 7, 7, 7, 7, 3]. What candidate and final…