Find the shortest queue with few calls
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Google's onsite coding round, last asked Apr 2026. It tests apis and optimization.
You have n queues (for example servers taking jobs). The only way to learn a queue's length is get_length(i), an expensive remote call, and lengths keep changing as jobs arrive and finish. Pick the shortest queue while making as few calls as you can, and explain the trade-off between the number of calls and how good the choice is.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
get_length(i: int) -> int— the current length of queuei,0 <= i < n. Each call is costly. -
shortest_exact(n: int) -> int— the index of a shortest queue (ties: lowest index). -
pick_queue(n: int, budget: int) -> int— choose a queue using at mostbudgetcalls, aiming for a short one.
Example
With current lengths [5, 2, 7, 2, 9]:
shortest_exact(5) -> 1 # 5 calls; queues 1 and 3 tie, lowest index wins
pick_queue(5, budget=2) -> the shorter of 2 random queues, for example queue 3 if it sampled 0 and 3
Constraints
-
nup to 10^4; a call takes about a millisecond or more. - Many clients pick queues at the same time.
Clarifying questions
- Do lengths change between calls? How fast?
- Do we need the exact shortest queue, or one that is short enough?
- Is there any cheaper signal: cached lengths, pushed updates, a central counter?
- How many clients choose at once? (A herd all choosing the same "shortest" queue makes it the longest.)
What a strong answer covers
- The exact answer needs all
ncalls in the worst case: any queue not asked about could be the shortest. Calls can run in parallel to cut latency, but not their count. - Sampling: ask
drandom queues and take the shortest. Withd = 2("power of two choices") the longest queue drops from aboutlog n / log log nto aboutlog log nabove average under random assignment, a large gain for one extra call. - Caching lengths with a timestamp, and refreshing only stale ones; the cost of stale data under load.
- The herd effect: many clients reading the same cached lengths all pick the same queue. Randomised sampling avoids it.
- Push instead of pull: queues report their lengths, or a central coordinator tracks them.
- Tests: ties, all equal, a queue that changes between calls.
Follow-ups
- Lengths only change by
+1or-1per step. Can you avoid re-asking every queue each time? - Queues have different service speeds. What should you compare?
- Find the
kshortest queues.
Where it's asked
- Google · Onsite coding · Last asked Apr 202645 min · Usually two rounds, mostly in person: whiteboard plus a Chromebook with Google Docs · No AI (a pilot code-comprehension round lets candidates use Gemini)
What it tests
apis · optimization
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
