#2187

Minimum Time to Complete Trips

Medium
ArrayBinary SearchBinary SearchGreedy
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n * m)
O(n log m)
Space
O(1)
O(1)
💡

Intuition

Time O(n log m)Space O(1)

Using binary search, we can efficiently find the minimum time required to complete the totalTrips by narrowing down the possible time range based on the number of trips completed in a given time.

⚙️

Algorithm

5 steps
  1. 1Step 1: Set low to 1 and high to the maximum time in the array multiplied by totalTrips.
  2. 2Step 2: While low is less than high, calculate mid as the average of low and high.
  3. 3Step 3: Count the total trips that can be completed in mid time using the formula sum(mid // t for t in time).
  4. 4Step 4: If the total trips are greater than or equal to totalTrips, set high to mid; otherwise, set low to mid + 1.
  5. 5Step 5: Return low as the minimum time required.
solution.py12 lines
1# Full working Python code
2
3def minTimeToCompleteTrips(time, totalTrips):
4    low, high = 1, min(time) * totalTrips
5    while low < high:
6        mid = (low + high) // 2
7        trips_completed = sum(mid // t for t in time)
8        if trips_completed >= totalTrips:
9            high = mid
10        else:
11            low = mid + 1
12    return low

Complexity note: The time complexity is O(n log m) where n is the number of buses and m is the maximum possible time to complete totalTrips. This is efficient because we reduce the search space logarithmically.

  • 1Binary search helps in optimizing the search for minimum time.
  • 2Understanding how to count trips efficiently is crucial.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.