Minimum Time to Repair Cars — LeetCode 2594 Python Solution

MediumArrayBinary Search
Problem
#2594
Reading time
2 min

The problem

You are given an integer array ranks representing the ranks of some mechanics. ranksi is the rank of the ith mechanic.

Example

Input
ranks = [4,2,3,1], cars = 10
Output
16
Explanation
- The first mechanic will repair two cars. The time required is 4 * 2 * 2 = 16 minutes.

Python solution

Python
class Solution:
    def repairCars(self, ranks: List[int], cars: int) -> int:
        def check(t: int) -> bool:
            return sum(int(sqrt(t // r)) for r in ranks) >= cars

        return bisect_left(range(ranks[0] * cars * cars), True, key=check)

Complexity

MeasureComplexity
TimeO(n \times \log M)
SpaceO(1) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 2594. Minimum Time to Repair Cars is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2594. Minimum Time to Repair Cars?
LeetCode 2594. Minimum Time to Repair Cars is rated Medium on LeetCode.
What is the time complexity of LeetCode 2594. Minimum Time to Repair Cars?
The Python solution on this page runs in O(n \times \log M).
What is the space complexity of LeetCode 2594. Minimum Time to Repair Cars?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2594. Minimum Time to Repair Cars cover?
LeetCode 2594. Minimum Time to Repair Cars is tagged Array and Binary Search on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview