Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Binary search

Earliest time a fleet completes its trips

Medium · Target 20 minutes · Binary search · Type asked atAmazonBloombergCitadel

Vehicle i needs time[i] units of time per trip and starts its next trip as soon as one ends. All vehicles start at time 0 and run independently. Return the smallest whole time t by which the vehicles together have completed at least totalTrips trips.

Examples

InputOutputWhy
time = [1, 2, 3], totalTrips = 53By time 3: 3 + 1 + 1 = 5 trips. By time 2: 2 + 1 + 0 = 3.
time = [2], totalTrips = 12
time = [5, 10, 10], totalTrips = 9255 + 2 + 2 = 9 by time 25.

Constraints

  • 1 ≤ time.length ≤ 10⁵
  • 1 ≤ time[i], totalTrips ≤ 10⁷

Hints

Hint 1

At time t, how many trips has vehicle i finished?

Hint 2

⌊t / time[i]⌋. Add them up: the count can only grow with t.

Hint 3

Upper bound: the fastest vehicle alone finishes totalTrips trips by min(time) × totalTrips. Search [1, that] for the first t with enough trips.

Where people lose marks

  • Using 32-bit integers for t: the upper bound reaches 10¹⁴.
  • Assuming the sum is small. Here each term is at most totalTrips, so 64 bits suffice; stopping as soon as the target is reached keeps the check safe in variants without that bound, and costs nothing.
  • Starting the search at 0 and returning 0 when totalTrips is positive: no trip ends at time 0.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.