FrontendPro

49Implement a priority-based task scheduler

mediumAbout 35 minutesCodingconcurrencyheapschedulingdata-structures

Problem

Implement a PriorityScheduler class. Tasks wait in a queue, and whenever a slot is free the highest-priority waiting task runs next.

  • new PriorityScheduler({ concurrency = 1 })
  • schedule(task, priority = 0): task is a function returning a promise or value. Returns a promise for its result. A higher number means more urgent.
  • size: the number of waiting tasks.
const scheduler = new PriorityScheduler({ concurrency: 2 });
scheduler.schedule(() => prefetchImages(), 0);
scheduler.schedule(() => loadVisibleRows(), 10); // runs before the prefetch if both are waiting

Requirements

  • Tasks with equal priority run in the order they were scheduled (FIFO).
  • Running tasks are never interrupted; priority only decides which waiting task starts next.
  • Use a binary heap, so scheduling and picking the next task are O(log n), even with thousands of waiting tasks.
  • A failing task rejects only its own promise.

Try it yourself

Write your solution, run it, then submit to check it against the tests.

solution.jsJavaScript

Press Run or ⌘ Enter to execute your code.

Step-by-step

Keeping a sorted array costs O(n) per insert. A binary heap keeps the most urgent item at index 0 with O(log n) insert and remove, which matters when thousands of tasks are queued.

Unlock the full solution

What's inside

  • Step-by-step
  • Approach
  • Solution
  • Complexity
  • Edge cases
  • Follow-up questions
  • Tests

Includes 2 code listings, 4 edge cases, 4 follow-up questions.

One-time payment by UPI, card or net banking. Launch price.

All 150 answersOne payment, yours forever