Data Structures & AlgorithmsVery hardProduct company OA

Problem: A single CPU receives tasks (enqueue time, duration). When idle it starts the available task with the shortest duration (ties: smaller index); if none is available it waits. Return the processing order.

Problem: A single CPU receives tasks (enqueue time, duration). When idle it starts the available task with the shortest duration (ties: smaller index); if none is available it waits. Return the processing order.
import heapq
def cpu_order(tasks):
    order = sorted(range(len(tasks)), key=lambda i: tasks[i][0])
    h, res, t, i = [], [], 0, 0
    while len(res) < len(tasks):
        if not h and t < tasks[order[i]][0]: t = tasks[order[i]][0]
        while i < len(order) and tasks[order[i]][0] <= t:
            j = order[i]; heapq.heappush(h, (tasks[j][1], j)); i += 1
        p, j = heapq.heappop(h); t += p; res.append(j)
    return res
print(cpu_order([(1, 4), (2, 2), (3, 1), (4, 3), (12, 2)]))
What is printed?
  1. A. [0, 1, 2, 3, 4]
  2. B. [0, 2, 1, 4, 3]
  3. C. [0, 2, 1, 3, 4]
  4. D. [2, 1, 0, 3, 4]

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

t = 1: only task 0 is available → runs to t = 5. By then tasks 1 (2), 2 (1), 3 (3) have arrived → shortest is 2 (t = 6), then 1 (t = 8), then 3 (t = 11). The CPU idles until 12 for task 4. Choosing by arrival order or ignoring idle time gives the other orders. O(n log n).

More Coding Interview Problems questions

Exams that ask this topic