LeetCode 2187: Minimum Time to Complete Trips Solution

Master LeetCode problem 2187 (Minimum Time to Complete Trips), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2187. Minimum Time to Complete Trips

Problem Explanation

Explanation:

To solve this problem, we need to find the minimum time required for all buses to complete at least totalTrips trips. We can approach this problem using binary search. We define a function numTripsCompleted that calculates the total number of trips completed by all buses at a given time t. Then, we perform binary search on the time range to find the minimum time that satisfies the condition of completing at least totalTrips trips.

  1. Algorithm:

    • Define a function numTripsCompleted that calculates the total number of trips completed by all buses at a given time t.
    • Perform binary search on the time range [1, 10^9] to find the minimum time that satisfies completing at least totalTrips trips.
  2. Time Complexity:

    • The time complexity of this approach is O(log(10^9) * n), where n is the number of buses.
  3. Space Complexity:

    • The space complexity is O(1) as we are not using any extra space other than a few variables.

:

Solution Code

class Solution {
    public int minTimeToCompleteTrips(int[] time, int totalTrips) {
        int left = 1, right = (int)1e9;
        
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (numTripsCompleted(time, mid) < totalTrips) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        
        return left;
    }
    
    private int numTripsCompleted(int[] time, int t) {
        int totalTrips = 0;
        for (int tripTime : time) {
            totalTrips += t / tripTime;
        }
        return totalTrips;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2187 (Minimum Time to Complete Trips)?

This page provides optimized solutions for LeetCode problem 2187 (Minimum Time to Complete Trips) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2187 (Minimum Time to Complete Trips)?

The time complexity for LeetCode 2187 (Minimum Time to Complete Trips) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2187 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2187 in Java, C++, or Python.

Back to LeetCode Solutions