#2594
Minimum Time to Repair Cars
MediumArrayBinary SearchBinary SearchGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log(max_time)) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log(max_time))Space O(1)
We can use binary search to find the minimum time required to repair all cars. By checking if a given time can repair all cars, we can efficiently narrow down the possible minimum time.
⚙️
Algorithm
5 steps- 1Step 1: Set low = 1 and high = max(ranks) * cars * cars (upper bound for time).
- 2Step 2: While low < high, calculate mid = (low + high) // 2.
- 3Step 3: Check if all cars can be repaired in 'mid' time using a helper function.
- 4Step 4: If yes, set high = mid; otherwise, set low = mid + 1.
- 5Step 5: Return low as the minimum time.
solution.py18 lines
1# Full working Python code
2
3def canRepairInTime(ranks, cars, time):
4 total_cars = 0
5 for r in ranks:
6 total_cars += int((time // r) ** 0.5)
7 return total_cars >= cars
8
9
10def minTimeToRepairCars(ranks, cars):
11 low, high = 1, max(ranks) * cars * cars
12 while low < high:
13 mid = (low + high) // 2
14 if canRepairInTime(ranks, cars, mid):
15 high = mid
16 else:
17 low = mid + 1
18 return lowℹ
Complexity note: The time complexity is O(n log(max_time)) because we are performing a binary search over time and checking the number of cars that can be repaired in O(n) time.
- 1Binary search can significantly reduce the time complexity.
- 2Understanding how to distribute tasks among workers is crucial.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.