Minimum Time to Complete Trips solution explained

Minimum Time to Complete Trips is a lower-bound binary search on time: by time T, a bus that needs t minutes per trip has finished T // t trips, so the fleet's total is a sum of quotients that never decreases as T grows. Search between 1 and the fastest bus's time multiplied by the trips needed, and return the first T whose total reaches the goal, in O(n log(min_t · goal)) time.

By Published 7 min read

Restating the task

A depot runs a fleet of buses. Bus i takes time[i] minutes to finish one trip, and as soon as it finishes it starts the next one. All buses start at minute 0 and run at the same time, independently of each other. You are given the number of trips the depot needs in total. Return the smallest whole number of minutes after which the combined count of finished trips is at least that number.

Fleets made up for this page
Trip timesTrips neededEarliest timeTrips done at that time
[2, 3, 7]563 + 2 + 0 = 5
[3, 4]6124 + 3 = 7; at 11 only 3 + 2 = 5
[1, 10]101010 + 1 = 11; at 9 only 9
[5, 5, 5]7153 + 3 + 3 = 9; at 14 only 6
[4]312One bus, three trips back to back
Fleets made up for this page. Scroll sideways on a small screen.

The [3, 4] row shows why the answer can overshoot the target count. Trips finish in bursts, so the first time that reaches six trips actually completes seven. You return the time, not a trip count, and you never need the count to match exactly.

Why this one gets asked

It looks like a scheduling simulation, and a simulation does produce the right answer. The trap is size: the target can be in the tens of millions, and so can each trip time. The interviewer wants to see you notice that you never need to know when individual trips finish, only how many have finished by some moment. That count is easy to compute and only grows with time, which turns the problem into a search over a number line.

Slow approach: simulate with a heap

Keep a min-heap of the next finish time for each bus. Pop the earliest one, count a trip, and push that bus back with its next finish time. After you have popped as many trips as you need, the last popped time is the answer. This is a correct and natural first idea, and it is better than stepping through the clock one minute at a time.

import heapq

def earliest_finish_slow(times, goal):
    events = [(t, t) for t in times]  # (next finish, trip length)
    heapq.heapify(events)
    finished_at = 0
    for _ in range(goal):
        finished_at, length = heapq.heappop(events)
        heapq.heappush(events, (finished_at + length, length))
    return finished_at
Event simulation, O(goal · log n) time and O(n) memory.

Its cost is tied to the number of trips, though. Ten million trips means ten million heap operations, which is slow in any language and painful in Python. Interviewers usually let you describe this version, then ask what happens when the goal is huge.

Main approach: binary search on time

Fix a moment T. A bus with trip length t has completed exactly T // t trips by then, because partial trips do not count. Add that over all buses and compare with the goal. If the total is enough at T, it is also enough at every later time, since no quotient can shrink. So the times that work form a suffix of the number line, and you want its first element.

Bounds come from two easy facts. Time 1 is the earliest possible answer. And the fastest bus by itself completes the goal by min(time) × goal, so that value always works and can serve as hi. Then run the usual lower-bound loop: if mid works, the answer is mid or earlier, so set hi to mid; if not, set lo to mid + 1. The loop ends with lo on the first working time.

def earliest_finish(times, goal):
    lo, hi = 1, min(times) * goal
    while lo < hi:
        mid = (lo + hi) // 2
        if sum(mid // t for t in times) >= goal:
            hi = mid
        else:
            lo = mid + 1
    return lo
Python: lower-bound search on time.
function earliestFinish(times, goal) {
  const enoughBy = (moment) => {
    let trips = 0;
    for (const t of times) {
      trips += Math.floor(moment / t);
      if (trips >= goal) return true;
    }
    return false;
  };
  let lo = 1;
  let hi = times.reduce((a, b) => Math.min(a, b)) * goal;
  while (lo < hi) {
    const mid = Math.floor((lo + hi) / 2);
    if (enoughBy(mid)) hi = mid;
    else lo = mid + 1;
  }
  return lo;
}
JavaScript: the same search, with an early exit in the count.

The early exit is not decoration in JavaScript. With a large mid and many fast buses, the full sum of quotients can pass 2 to the power 53, where plain numbers stop being exact integers. Stopping once the count reaches the goal keeps every value well inside the safe range, and it saves work. In Java or C++ the same concern shows up as 64-bit overflow, and the same early exit fixes it.

Trace on a small fleet

Times [2, 3, 7], goal 5. The fastest bus takes 2, so hi = 10 and lo = 1. mid = 5 gives 2 + 1 + 0 = 3 trips, not enough, so lo = 6. mid = 8 gives 4 + 2 + 1 = 7, enough, so hi = 8. mid = 7 gives 3 + 2 + 1 = 6, enough, so hi = 7. mid = 6 gives 3 + 2 + 0 = 5, enough, so hi = 6. lo and hi meet at 6.

Complexity at a glance

n buses, fastest trip m, goal g
VersionTimeSpaceBreaks down when
Minute-by-minute clockO(n · m · g)O(1)Almost immediately
Heap of next finish timesO(g log n)O(n)g reaches the millions
Binary search on TO(n log(m · g))O(1)Rarely; about 50 checks even for very large bounds
n buses, fastest trip m, goal g. Scroll sideways on a small screen.

Cases to run before you say done

  • One bus: the answer is its trip time multiplied by the goal, which is exactly hi.
  • A goal of 1: the answer is the fastest trip time.
  • Many identical buses: trips finish in big batches, so the answer is a multiple of the common time.
  • One very fast bus among slow ones: the fast bus dominates, and the slow ones may add nothing before the answer.
  • Very large goal and trip times: hi can reach around 10 to the 14th, so use 64-bit integers in typed languages.

Where candidates slip

  • Using the slowest bus, or the average, for hi. The fastest bus is the one that guarantees the bound works.
  • Counting a partial trip. Integer division already drops it, so do not round up.
  • Writing lo = mid on success in a lower-bound search. That is the template for the last value that works, not the first.
  • Summing every quotient without a cap and overflowing in Java, C++ or JavaScript.
  • Sorting the buses first. The order does not affect the count, so it is wasted time.

Talking through it

Fictional example

A compact explanation for the interviewer
Candidate
I could simulate finishes with a heap, but that is one heap operation per trip, and the goal can be in the millions.
Candidate
Instead I ask how many trips are done by time T. That is the sum of T divided by each trip time, rounded down, and it only grows with T.
Candidate
So I binary search for the first T where that sum reaches the goal. The fastest bus alone gives a safe upper bound of its time times the goal.

Neighbors in this set

Compare this with Maximum Candies Allocated to K Children: the check is nearly the same sum of quotients, but there you want the largest share that works and here the smallest time. The next problem in the set, Number of Islands II, moves from searching on answers to union-find. Background on search patterns is on the algorithm interview questions page.

Natively during practice

If you practice with Natively, it can capture a problem like this from a screenshot and offer a plan and code, a handy second opinion once you have your own version written. It also records a running transcript of a mock session on your machine, which lets you review whether you named the heap idea before moving to the search. Details on an AI interview assistant for Mac and Windows.

Questions people ask

What is the optimal solution to Minimum Time to Complete Trips?

Binary search on time. By time T a bus with trip length t has done T // t trips, so check whether the sum over all buses reaches the goal and search for the first T where it does.

What upper bound should the binary search use?

The fastest trip time multiplied by the number of trips needed. The fastest bus alone finishes the goal by then, so that time always works.

What is the time complexity?

O(n log(m · g)), where n is the number of buses, m the fastest trip time and g the goal. Each check is one pass over the buses. Extra space is O(1).

Why not simulate the trips with a heap?

A heap works and is a good first idea, but it costs one heap operation per trip. When the goal is in the millions that is far slower than about fifty linear checks.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP