Data Structures & AlgorithmsVery hardGoogle · Flipkart interview

Problem: A single-threaded CPU receives tasks [enqueueTime, processingTime]. When idle it runs the available task with the shortest processing time (ties: smaller index); it never preempts. Output the execution order.

Problem: A single-threaded CPU receives tasks [enqueueTime, processingTime]. When idle it runs the available task with the shortest processing time (ties: smaller index); it never preempts. Output the execution order.
import heapq
def order(tasks):
    idx = sorted(range(len(tasks)), key=lambda i: tasks[i][0])
    t, i, h, out = 0, 0, [], []
    while len(out) < len(tasks):
        if not h and t < tasks[idx[i]][0]: t = tasks[idx[i]][0]
        while i < len(idx) and tasks[idx[i]][0] <= t:
            heapq.heappush(h, (tasks[idx[i]][1], idx[i])); i += 1
        p, j = heapq.heappop(h); t += p; out.append(j)
    return out
print(order([[2, 3], [0, 5], [3, 1], [4, 2], [6, 1]]))
What is printed?
  1. A. [1, 0, 2, 3, 4]
  2. B. [1, 2, 4, 3, 0]
  3. C. [1, 2, 3, 4, 0]
  4. D. [2, 4, 3, 0, 1]

Correct answer: B. [1, 2, 4, 3, 0]

At t = 0 only task 1 is available, so it runs to t = 5 even though shorter tasks arrive meanwhile (no preemption). At t = 5 tasks 0 (3), 2 (1), 3 (2) are waiting: run 2 (t = 6), then 4 has arrived (1) and runs (t = 7), then 3 (t = 9), then 0.

More Coding Interview Problems questions

Exams that ask this topic