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?- A. [1, 0, 2, 3, 4]
- B. [1, 2, 4, 3, 0]
- C. [1, 2, 3, 4, 0]
- 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
- Problem: A min-stack supports push, pop, top and getMin in O(1) by storing (value, current minimum) pairs. python st, out = [], [] def…
- Problem: Josephus problem: n people in a circle, every k-th person is eliminated; find the 1-based position of the survivor. python def…
- Problem: Count permutations of 1..n where, for every position i (1-based), the value is divisible by i or i is divisible by the value…
- Problem: Each candidate can be used at most ONCE and the list has duplicates; count the distinct combinations that sum to the target…
- Problem: Divide two integers without , / or %, truncating toward zero, using doubling (shifts). python def divide(a, b): neg = (a < 0) !=…
- Problem: Traverse a matrix along anti-diagonals, alternating direction (up-right first). python def diag(m): R, C = len(m), len(m[0]); out…