CPU Scheduling - Google Top Interview Questions
Problem Statement :
You are given a two-dimensional list of integers tasks. Each element contains [id, queue_time, duration] which represents a CPU task with id id, queued at time queue_time, that will run for duration amount of time. All tasks have unique ids. Given that the CPU scheduler will run a job that is currently in the queue with the lowest duration first, return the order of job ids that will be processed. If there's more than one job with the lowest duration, then it will run the job with lowest id first. Constraints n ≤ 100,000 where n is the length of tasks Example 1 Input tasks = [ [0, 1, 5], [1, 1, 5], [2, 2, 2] ] Output [0, 2, 1] Explanation At time 1 we run task 0 since it's the only one that's queued. It runs for 5 units of time. Then we have tasks 1 and 2 that are queued. We run task 2 first because it has lower duration. Example 2 Input tasks = [ [0, 1, 5], [1, 1, 5] ] Output [0, 1] Explanation Both tasks are queued up at the same time and both of them have the same duration. Since task 0 has lower id, we run it first.
Solution :
Solution in C++ :
bool timesort(vector<int>& a, vector<int>& b) {
return a[1] < b[1];
}
vector<int> solve(vector<vector<int>>& tasks) {
vector<int> ret;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> queued;
int t = 0;
int n = tasks.size();
sort(tasks.rbegin(), tasks.rend(), timesort);
while (ret.size() < n) {
if (queued.size() == 0) t = max(t, tasks.back()[1]);
while (tasks.size() && tasks.back()[1] <= t) {
queued.emplace(tasks.back()[2], tasks.back()[0]);
tasks.pop_back();
}
ret.push_back(queued.top().second);
t += queued.top().first;
queued.pop();
}
return ret;
}
Solution in Java :
import java.util.*;
class Solution {
/*
Lowest duration first.
Return the order of jobs ids that will be processed
Sort based on duration first
Basically, having 2 priority queue. Set the first priority queue based on the queueTime,
the second priority queue based on the duration. We always put the first priority queue as
the single source of truth. The second priority queue will execute the task from the first
priority queue.
We will always pop the first priority queue and insert that value to the second priority
queue. The second priority queue execute the task and calculate the next execution time. This
is where the current time unit get a bit tricky. We get the end of the range starting from
the first queue time.
We will poll all the elements in the first priority queue until it the peek value that is <=
endRange.
Each of the poll element from the 2nd PQ we will insert to the result array, and return that
result array at the end. We will keep polling until both PQ is empty.
Then, we will increment the queue range based on the maximum of the following two task:
1. current end range + task[2] which is the duration of the current task that is finish
executing.
2. the current queue task + the current task duration
For instance:
[ [0, 1, 5], [1, 1, 5], [2, 2, 2] ]
--> secondPQ has [[0,1,5],[1,1,5]]
--> initial endRange = 1 (queueTime for [0, 1, 5])
--> initial execution endRange = 1 + 5 (which ends
at 6)
--> secondPQ has [[2,2,2],[1,1,5]]
--> second execution endRange = max (6 +2, 2+2)
--> secondPQ has [1,1,5]
--> execute [1,1,5]
Cases:
- If there are multiple 0 duration with different queue time [[0,1,0], [1,3,0],[2,5,0]] -->
[0,1,2]
- If duration is shorter in the later queue time, and longer in the beginning queue time
[[0,1,6],[1,3,5],[2,5,4],[3,6,2]] --> [0,3,2,1]
- queue time doesn't interleave [[0,1,4],[1,3,3],[2,4,3],[3,6,2]] --> [0,1,3,2]
- If the duration of the initial queue time is smaller than the duration in the later queue
time [[0,1,1],[1,2,2],[2,3,3]] --> [0,1,2]
- If the duration of the initial queue time is interleave with the duration of the later
queue time. [[0,1,6],[1,3,5],[2,5,7],[3,6,3]] --> [0, 3, 1, 2]
- If the both duration and queue time is the same but different id, will be queue up from id
first:
[[0, 1, 5],[1, 1, 5]] -- [0,1]
- Cases where the from duration needs to be the initial queue time: tasks = [[0, 1, 2],[1,
3, 1],[2, 2, 3],[3, 1, 0]]
- Cases if the duration is the same and the queueTime is the same, we set it to the id in
queueTimeQ
*/
public int[] solve(int[][] tasks) {
/*
Having a pq to store all the values of queueTime.
Pop the queue time and get all the value of that queue time into the q task.
Then the queue task will calculate the next max value, and will pop all the
value from the pq from that max value
*/
PriorityQueue<int[]> queueTimeQ = new PriorityQueue<>(new Comparator<int[]>() {
@Override
public int compare(int[] a, int[] b) {
if (a[1] == b[1]) {
return (a[2] != b[2]) ? a[2] - b[2] : a[0] - b[0];
}
else
return a[1] - b[1];
}
});
PriorityQueue<int[]> qExecution = new PriorityQueue<>(new Comparator<int[]>() {
@Override
public int compare(int[] a, int[] b) {
if (a[2] == b[2]) {
return a[0] - b[0];
}
else
return a[2] - b[2];
}
});
int[] res = new int[tasks.length];
// all the queuedTime
// TreeSet<Integer> treeSet = new TreeSet<>();
for (int i = 0; i < tasks.length; i++) {
queueTimeQ.offer(tasks[i]);
}
int i = 0;
int to =
(!queueTimeQ.isEmpty()) ? queueTimeQ.peek()[1] : 0; // set it to the initialQueueTime
while (!queueTimeQ.isEmpty()) {
qExecution.offer(queueTimeQ.poll());
while (!qExecution.isEmpty()) {
int[] task = qExecution.poll();
res[i++] = task[0];
// get the to value, which is from + the res[2], we also need to check if the
// initial task is more than the end task we need to set whoever the end range is
// the largest
to = Math.max(to + task[2], task[1] + task[2]);
// check for queue time that is less than or equal to `to` in the queueTimeQ
while (!queueTimeQ.isEmpty() && queueTimeQ.peek()[1] <= to)
qExecution.offer(queueTimeQ.poll());
}
}
return res;
}
}
Solution in Python :
class Solution:
def solve(self, tasks):
tasks.sort(key=lambda x: (x[1], x[2], x[0]))
idx = 0
time = tasks[0][1]
heap = []
res = []
while idx < len(tasks):
while idx < len(tasks) and tasks[idx][1] <= time:
heappush(heap, (tasks[idx][2], tasks[idx][0]))
idx += 1
if not heap:
time = tasks[idx][1]
continue
dur, ID = heappop(heap)
res.append(ID)
time += dur
while heap:
res.append(heappop(heap)[1])
return res
View More Similar Problems
Reverse a doubly linked list
This challenge is part of a tutorial track by MyCodeSchool Given the pointer to the head node of a doubly linked list, reverse the order of the nodes in place. That is, change the next and prev pointers of the nodes so that the direction of the list is reversed. Return a reference to the head node of the reversed list. Note: The head node might be NULL to indicate that the list is empty.
View Solution →Tree: Preorder Traversal
Complete the preorder function in the editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's preorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the preOrder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the tree's
View Solution →Tree: Postorder Traversal
Complete the postorder function in the editor below. It received 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's postorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the postorder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the
View Solution →Tree: Inorder Traversal
In this challenge, you are required to implement inorder traversal of a tree. Complete the inorder function in your editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's inorder traversal as a single line of space-separated values. Input Format Our hidden tester code passes the root node of a binary tree to your $inOrder* func
View Solution →Tree: Height of a Binary Tree
The height of a binary tree is the number of edges between the tree's root and its furthest leaf. For example, the following binary tree is of height : image Function Description Complete the getHeight or height function in the editor. It must return the height of a binary tree as an integer. getHeight or height has the following parameter(s): root: a reference to the root of a binary
View Solution →Tree : Top View
Given a pointer to the root of a binary tree, print the top view of the binary tree. The tree as seen from the top the nodes, is called the top view of the tree. For example : 1 \ 2 \ 5 / \ 3 6 \ 4 Top View : 1 -> 2 -> 5 -> 6 Complete the function topView and print the resulting values on a single line separated by space.
View Solution →