#2589

Minimum Time to Complete All Tasks

Hard
ArrayBinary SearchStackGreedySortingGreedySorting
LeetCode ↗

Approaches

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

Intuition

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

The optimal solution sorts the tasks by their end times and uses a greedy approach to allocate the required durations efficiently. This minimizes the total time the computer needs to be on by ensuring tasks are scheduled in the most compact way possible.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the tasks by their end time.
  2. 2Step 2: Initialize a variable to track the current time and another for the total active time.
  3. 3Step 3: For each task, check if it can fit into the available time slots and allocate the required duration, updating the total active time accordingly.
solution.py13 lines
1# Full working Python code
2
3def minTime(tasks):
4    tasks.sort(key=lambda x: x[1])
5    total_time = 0
6    current_time = 0
7    for start, end, duration in tasks:
8        if current_time < start:
9            current_time = start
10        available_time = min(end, current_time + duration) - current_time
11        total_time += available_time
12        current_time += available_time
13    return total_time

Complexity note: The sorting step takes O(n log n) time, and the subsequent iteration through the tasks takes O(n), leading to an overall complexity dominated by the sort operation.

  • 1Sorting tasks by end time allows for efficient scheduling.
  • 2Greedy allocation of time minimizes total active time.

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