630. Course Schedule III
HardSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks for the maximum number of courses we can take, given their durations and deadlines. We start on day 1 and can only take one course at a time. This is a scheduling problem that can be framed as selecting a maximum-sized subset of courses that can be completed within their deadlines.
Solution
Course Schedule III in Python
import heapq
class Solution:
def scheduleCourse(self, courses: List[List[int]]) -> int:
# Sort courses by their deadlines (lastDay).
# This is a greedy approach where we prioritize courses that finish earlier.
courses.sort(key=lambda x: x[1])
# Use a max-heap to keep track of the durations of the courses we've taken.
# In Python, heapq is a min-heap, so we store negative values to simulate a max-heap.
pq = []
currentTime = 0
for duration, lastDay in courses:
# Add the current course's duration to our timeline and priority queue.
currentTime += duration
heapq.heappush(pq, -duration)
# If the currentTime exceeds the deadline of the current course,
# we need to remove a course. To make the most room for future courses,
# we remove the one with the longest duration.
if currentTime > lastDay:
# Pop the longest duration (which is the smallest value in the min-heap).
longest_duration = -heapq.heappop(pq)
currentTime -= longest_duration
# The size of the priority queue is the number of courses we can take.
return len(pq)
Course Schedule III in Java
class Solution {
public int scheduleCourse(int[][] courses) {
// Sort courses by their deadlines (lastDayi).
// This is a greedy approach where we prioritize courses that finish earlier.
Arrays.sort(courses, (a, b) -> a[1] - b[1]);
// Use a max-heap (PriorityQueue with a reverse order comparator) to keep track of
// the durations of the courses we've taken.
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
int currentTime = 0;
for (int[] course : courses) {
int duration = course[0];
int lastDay = course[1];
// Add the current course's duration to our timeline and priority queue.
currentTime += duration;
pq.offer(duration);
// If the currentTime exceeds the deadline of the current course,
// we need to remove a course. To make the most room for future courses,
// we remove the one with the longest duration.
if (currentTime > lastDay) {
currentTime -= pq.poll();
}
}
// The size of the priority queue is the number of courses we can take.
return pq.size();
}
}
Course Schedule III in C++
class Solution {
public:
int scheduleCourse(vector<vector<int>>& courses) {
// Sort courses by their deadlines (lastDayi).
// This is a greedy approach where we prioritize courses that finish earlier.
sort(courses.begin(), courses.end(), [](const vector<int>& a, const vector<int>& b) {
return a[1] < b[1];
});
// Use a max-heap to keep track of the durations of the courses we've taken.
// This helps in quickly finding the course with the longest duration to remove if needed.
priority_queue<int> pq;
int currentTime = 0;
for (const auto& course : courses) {
int duration = course[0];
int lastDay = course[1];
// Add the current course's duration to our timeline and priority queue.
currentTime += duration;
pq.push(duration);
// If the currentTime exceeds the deadline of the current course,
// we need to remove a course. To make the most room for future courses,
// we remove the one with the longest duration.
if (currentTime > lastDay) {
currentTime -= pq.top();
pq.pop();
}
}
// The size of the priority queue is the number of courses we can take.
return pq.size();
}
};
Course Schedule III in TypeScript
/**
* A simple MaxPriorityQueue implementation for environments without a standard library.
*/
class MaxPriorityQueue {
private heap: number[] = [];
public size(): number {
return this.heap.length;
}
public isEmpty(): boolean {
return this.size() === 0;
}
public push(val: number): void {
this.heap.push(val);
this.siftUp(this.heap.length - 1);
}
public pop(): number {
if (this.isEmpty()) {
throw new Error("Cannot pop from an empty queue.");
}
this.swap(0, this.heap.length - 1);
const val = this.heap.pop()!;
if (!this.isEmpty()) {
this.siftDown(0);
}
return val;
}
public top(): number {
if (this.isEmpty()) {
throw new Error("Cannot peek from an empty queue.");
}
return this.heap[0];
}
private parent(i: number): number {
return Math.floor((i - 1) / 2);
}
private leftChild(i: number): number {
return 2 * i + 1;
}
private rightChild(i: number): number {
return 2 * i + 2;
}
private swap(i: number, j: number): void {
[this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]];
}
private siftUp(i: number): void {
while (i > 0 && this.heap[this.parent(i)] < this.heap[i]) {
this.swap(this.parent(i), i);
i = this.parent(i);
}
}
private siftDown(i: number): void {
let maxIndex = i;
const left = this.leftChild(i);
if (left < this.size() && this.heap[left] > this.heap[maxIndex]) {
maxIndex = left;
}
const right = this.rightChild(i);
if (right < this.size() && this.heap[right] > this.heap[maxIndex]) {
maxIndex = right;
}
if (i !== maxIndex) {
this.swap(i, maxIndex);
this.siftDown(maxIndex);
}
}
}
function scheduleCourse(courses: number[][]): number {
// Sort courses by their deadlines (lastDay).
// This is a greedy approach where we prioritize courses that finish earlier.
courses.sort((a, b) => a[1] - b[1]);
// Use a max-heap to keep track of the durations of the courses we've taken.
const pq = new MaxPriorityQueue();
let currentTime = 0;
for (const course of courses) {
const duration = course[0];
const lastDay = course[1];
// Add the current course's duration to our timeline and priority queue.
currentTime += duration;
pq.push(duration);
// If the currentTime exceeds the deadline of the current course,
// we need to remove a course. To make the most room for future courses,
// we remove the one with the longest duration.
if (currentTime > lastDay) {
currentTime -= pq.pop();
}
}
// The size of the priority queue is the number of courses we can take.
return pq.size();
}
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.