Pick the Starting Depot for a Surface Delivery Van Loop

Last updated: November 29, 2026

Quick Overview

A van drives a fixed circular route through n depots; depot i provides `charge[i]` units of battery and driving from depot i to the next costs `cost[i]`. Return the index of the depot where the van can start with an empty battery and complete the loop, or -1 if no start works (assume the answer is unique when it exists).

Microsoft
Coding & Algorithms
Software Engineer
Microsoft
November 29, 2026
Software Engineer
Technical Screen
Coding & Algorithms
Medium

0

0

0 solved


A van drives a fixed circular route through n depots; depot i provides `charge[i]` units of battery and driving from depot i to the next costs `cost[i]`. Return the index of the depot where the van can start with an empty battery and complete the loop, or -1 if no start works (assume the answer is unique when it exists).

A classic greedy question that Microsoft interviewers often reframe around logistics or device fleets. They want the one-pass argument for discarding failed start ranges, not an O(n^2) simulation.

What the Interviewer Expects
  • Check feasibility with total charge versus total cost
  • Explain why a failure at i rules out every start from the current start to i
  • Implement an O(n) single pass
  • Trace an example and handle the single depot case
  • Discuss what changes if multiple starts are valid
Key Topics to Cover
greedy
prefix sums
circular arrays
gas station
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • How would you return all valid starting depots?
  • What if the battery has a maximum capacity?
  • What if the route is not circular but you can pick any contiguous segment?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements
  • Inputs: arrays charge and cost of equal length n.
  • The van starts at some depot with zero battery, collects charge[i], then spends cost[i] to reach depot i + 1 (wrapping around).
  • Battery ...
High-Level Design

Two facts drive the solution.

  1. If sum(charge) < sum(cost), no start can work because the loop consumes more than it supplies.
  2. If we start at s and the running balance first goes negative after...

Submit Your Answer
Markdown supported