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 :



title-img




                        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

Palindromic Subsets

Consider a lowercase English alphabetic letter character denoted by c. A shift operation on some c turns it into the next letter in the alphabet. For example, and ,shift(a) = b , shift(e) = f, shift(z) = a . Given a zero-indexed string, s, of n lowercase letters, perform q queries on s where each query takes one of the following two forms: 1 i j t: All letters in the inclusive range from i t

View Solution →

Counting On a Tree

Taylor loves trees, and this new challenge has him stumped! Consider a tree, t, consisting of n nodes. Each node is numbered from 1 to n, and each node i has an integer, ci, attached to it. A query on tree t takes the form w x y z. To process a query, you must print the count of ordered pairs of integers ( i , j ) such that the following four conditions are all satisfied: the path from n

View Solution →

Polynomial Division

Consider a sequence, c0, c1, . . . , cn-1 , and a polynomial of degree 1 defined as Q(x ) = a * x + b. You must perform q queries on the sequence, where each query is one of the following two types: 1 i x: Replace ci with x. 2 l r: Consider the polynomial and determine whether is divisible by over the field , where . In other words, check if there exists a polynomial with integer coefficie

View Solution →

Costly Intervals

Given an array, your goal is to find, for each element, the largest subarray containing it whose cost is at least k. Specifically, let A = [A1, A2, . . . , An ] be an array of length n, and let be the subarray from index l to index r. Also, Let MAX( l, r ) be the largest number in Al. . . r. Let MIN( l, r ) be the smallest number in Al . . .r . Let OR( l , r ) be the bitwise OR of the

View Solution →

The Strange Function

One of the most important skills a programmer needs to learn early on is the ability to pose a problem in an abstract way. This skill is important not just for researchers but also in applied fields like software engineering and web development. You are able to solve most of a problem, except for one last subproblem, which you have posed in an abstract way as follows: Given an array consisting

View Solution →

Self-Driving Bus

Treeland is a country with n cities and n - 1 roads. There is exactly one path between any two cities. The ruler of Treeland wants to implement a self-driving bus system and asks tree-loving Alex to plan the bus routes. Alex decides that each route must contain a subset of connected cities; a subset of cities is connected if the following two conditions are true: There is a path between ever

View Solution →