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?- A. [0, 1, 2, 3, 4]
- B. [0, 2, 1, 4, 3]
- C. [0, 2, 1, 3, 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
- Problem: Walk along buildings of given heights; climbing up by d needs d bricks or one ladder (going down is free). Return the furthest…
- Problem: Find the smallest range [lo, hi] that contains at least one number from each of k sorted lists (min-heap of one pointer per list…
- Problem: Choose the root(s) that minimise the height of an unrooted tree. Repeatedly strip all current leaves; the last 1 or 2 nodes are…
- Problem: Count the strongly connected components of a directed graph with Kosaraju's algorithm (DFS finishing order, then DFS on the…
- Problem: Stones sit on grid points; a stone may be removed if another remaining stone shares its row or column. Maximum removable = stones…
- Problem: Build row k of Pascal's triangle (row 0 = [1]) by adding neighbouring entries of the previous row. python def pascalrow(k): row =…