Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Binary search

The slowest rate that clears every queue in time

Medium · Target 20 minutes · Binary search · Type asked atGoogleAmazonOptiver

A worker has several queues of tasks; piles[i] is the number of tasks in queue i. Each hour the worker picks one queue and completes up to k tasks from it; if the queue has fewer than k left, the worker finishes it and rests for the rest of that hour. Return the smallest integer rate k at which every queue is finished within h hours.

Examples

InputOutputWhy
piles = [3, 6, 7, 11], h = 84At 4 per hour: 1 + 2 + 2 + 3 = 8 hours. At 3: 1 + 2 + 3 + 4 = 10.
piles = [30, 11, 23, 4, 20], h = 530One hour per queue, so the rate must cover the largest queue.
piles = [30, 11, 23, 4, 20], h = 623

Constraints

  • 1 ≤ piles.length ≤ 10⁴
  • piles.length ≤ h ≤ 10⁹
  • 1 ≤ piles[i] ≤ 10⁹

Hints

Hint 1

For a given k, how many hours does the work take? Each queue is separate.

Hint 2

Queue i takes ⌈piles[i] / k⌉ hours. The total never increases as k increases. What does that make "the total is at most h"?

Hint 3

A monotone test over k ∈ [1, max(piles)]: false, then true. Search for the first true.

Where people lose marks

  • Computing ⌈p / k⌉ with floating-point division, which can round wrongly for large p.
  • Summing the hours in a 32-bit integer.
  • Starting the search at 0, which divides by zero.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.