Python 0630.py
class Solution:
def scheduleCourse(self, courses: List[List[int]]) -> int:
# sort by lastday
ordered = [ ( lastday, duration ) for duration, lastday in courses ]
ordered.sort()
# remove impossible courses
while ordered and ordered[0][0] < ordered[0][1]:
ordered.pop(0)
# attended courses
taken = [] # max-heap
now = 0
for lastday, duration in ordered:
# try attending the course
heappush(taken, -duration)
now += duration
while taken and now > lastday:
# remove longest courses (can be the current course !)
longest = -heappop(taken) # max-heap
now -= longest
return len(taken)
Difficulty
and has an acceptance rate of about 41% (300k+ submissions).
Typical patterns to solve this problem:
- Array
- Greedy
- Heap (Priority Queue)
- Sorting
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the classic “course schedule” problem by selecting the maximum number of courses that can be completed before their respective deadlines. It follows a greedy strategy combined with a max-heap to keep the total time spent as low as possible while respecting deadline constraints. The algorithm proceeds through distinct phases: sorting the input, discarding courses that are impossible from the start, iteratively attempting to take each course, and discarding the longest taken course whenever the current schedule exceeds a deadline.
Sorting and Preparation
The first step transforms the list of [duration, lastday] pairs into a list of (lastday, duration) tuples and sorts them by deadline. This ordering guarantees that courses with earlier deadlines are considered before later ones, which is essential for the greedy approach.
ordered = [(lastday, duration) for duration, lastday in courses]
ordered.sort()
By sorting once at the beginning, the algorithm avoids repeated scans of the unsorted input and ensures that later decisions are made with a globally consistent view of deadline priorities.
Removing Impossible Courses
Before the main loop, the code eliminates any course whose duration already exceeds its deadline. Such a course can never be part of a feasible schedule, so removing it early reduces unnecessary heap operations.
while ordered and ordered[0][0] < ordered[0][1]:
ordered.pop(0)
The loop continues until the first remaining course satisfies the basic feasibility condition, effectively pruning the input to a set of potentially viable courses.
Greedy Selection with Max-Heap
The core of the algorithm iterates over the sorted courses. For each course, it tentatively adds the course’s duration to a running total now and pushes the negative duration onto a heap named taken. Using negative values turns Python’s min-heap implementation into a max-heap, allowing quick access to the longest duration among the selected courses.
taken = [] # max-heap (implemented with negative values)
now = 0
for lastday, duration in ordered:
heappush(taken, -duration)
now += duration
while taken and now > lastday:
longest = -heappop(taken) # remove the longest course
now -= longest
If adding the current course causes the accumulated time now to exceed the current deadline lastday, the inner loop removes the longest course from the heap. This removal may discard the just-added course or a previously taken one, whichever has the greatest duration. By always discarding the longest duration, the algorithm minimizes the total time spent while preserving the number of courses taken.
When the inner loop finishes, the schedule up to the current deadline is feasible. The heap taken therefore always contains a set of courses that can be completed within their respective deadlines, and its size reflects the number of courses successfully scheduled so far.
Edge Cases Handled
The implementation gracefully handles several edge conditions:
- Courses whose duration exceeds their own deadline are filtered out before any heap activity, preventing futile attempts to schedule them.
- When multiple courses share the same deadline, the sorted order ensures they are processed together, and the heap removal logic automatically selects the optimal subset based on duration.
- If the current course itself is the longest among those taken, the inner loop can immediately remove it, effectively skipping that course without affecting earlier selections.
- An empty input list results in an empty
orderedlist, bypassing all loops and returning zero, which correctly represents that no courses can be taken. - The while-condition
taken and now > lastdayguarantees that the removal step only runs when there is at least one course in the heap and the schedule is actually infeasible, avoiding unnecessary heap operations.
Performance Optimizations
The algorithm incorporates several practical optimizations:
- Sorting is performed once, establishing a deterministic processing order that eliminates the need for repeated comparisons during iteration.
- The use of a heap provides logarithmic-time insertion and removal of the longest duration, which is far more efficient than scanning the entire set of taken courses on each deadline violation.
- By storing negative durations, the code leverages the built-in
heapqmodule without requiring a custom max-heap implementation, reducing overhead. - The early removal of impossible courses shrinks the input size for the main loop, decreasing the number of heap pushes and pops.
- The inner removal loop runs only when the schedule becomes infeasible, and each iteration strictly reduces the total time, ensuring that the loop terminates quickly even in worst-case scenarios.
Overall, the combination of a single sort, a max-heap for dynamic adjustments, and early pruning of hopeless courses yields an implementation that efficiently computes the maximum number of courses that can be completed before their deadlines.
ELI5 - Simplified Explanation
Imagine a big box of school subjects you want to learn. Each subject has two rules. The first rule is how long it takes to finish learning it, and the second rule is a deadline for when you must be done.
First, the code organizes all the subjects by their deadlines, putting the ones that finish earliest at the front of the line. Before starting, it looks at the list and throws away any subject that is impossible to finish because its deadline comes before the time it would take to even complete the work.
Then, the code starts collecting the subjects onto a tray. It keeps track of the current time by adding up the duration of every subject on the tray. If the total time spent exceeds the deadline for a subject, the code performs a clever trick. It looks through all the subjects currently on the tray, finds the one that took the longest time to learn, and takes it off. By removing the longest subject, more time becomes available, which might make it possible to fit other subjects into the schedule. This way, the goal is to keep as many subjects as possible on the tray while always respecting the deadline for each one.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||||
| WalkCCC | C++ | Java | Python | ||||||||
| leetcode.ca | C++ | Java | Python | Go | TS | ||||||
| LeetcodeHelp | C++ | Java | Python | ||||||||
| Progiez | C++ | Java | Python | ||||||||
| github | black-shadows | C++ | |||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JS | ||||||||||
| fpdjsns | C++ | ||||||||||
| fsq | C++ | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JS | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| vthwang | Java | ||||||||||
| wisdompeak | C++ | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JavaScript | ||||||||||
| fpdjsns | C++ | ||||||||||
| fsq | C++ | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| vthwang | Java | ||||||||||
| wisdompeak | C++ | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 207: Course Schedule
- problem 210: Course Schedule II
- problem 2050: Parallel Courses III
Solved On The Same Day
- problem 1217: Minimum Cost to Move Chips to The Same Position
- problem 1221: Split a String in Balanced Strings
- problem 1323: Maximum 69 Number
- problem 1710: Maximum Units on a Truck
- problem 969: Pancake Sorting
- problem 991: Broken Calculator
- problem 1605: Find Valid Matrix Given Row and Column Sums
- problem 1425: Constrained Subsequence Sum
- problem 2147: Number of Ways to Divide a Long Corridor
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality