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
Left Rotation
A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. Given an integer, d, rotate the array that many steps left and return the result. Example: d=2 arr=[1,2,3,4,5] After 2 rotations, arr'=[3,4,5,1,2]. Function Description: Complete the rotateLeft function in the editor below. rotateLeft has the following parameters: 1. int d
View Solution →Sparse Arrays
There is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings. Return an array of the results. Example: strings=['ab', 'ab', 'abc'] queries=['ab', 'abc', 'bc'] There are instances of 'ab', 1 of 'abc' and 0 of 'bc'. For each query, add an element to the return array, results=[2,1,0]. Fun
View Solution →Array Manipulation
Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each of the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array. Example: n=10 queries=[[1,5,3], [4,8,7], [6,9,1]] Queries are interpreted as follows: a b k 1 5 3 4 8 7 6 9 1 Add the valu
View Solution →Print the Elements of a Linked List
This is an to practice traversing a linked list. Given a pointer to the head node of a linked list, print each node's data element, one per line. If the head pointer is null (indicating the list is empty), there is nothing to print. Function Description: Complete the printLinkedList function in the editor below. printLinkedList has the following parameter(s): 1.SinglyLinkedListNode
View Solution →Insert a Node at the Tail of a Linked List
You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head node of the linked list formed after inserting this new node. The given head pointer may be null, meaning that the initial list is empty. Input Format: You have to complete the SinglyLink
View Solution →Insert a Node at the head of a Linked List
Given a pointer to the head of a linked list, insert a new node before the head. The next value in the new node should point to head and the data value should be replaced with a given value. Return a reference to the new head of the list. The head pointer given may be null meaning that the initial list is empty. Function Description: Complete the function insertNodeAtHead in the editor below
View Solution →