AlgoMaster Logo
AlgoMasterDesign a Least Requests Load Balancermedium

Design a Least Requests Load Balancer

medium

Requests often have different durations. A backend still processing long requests should receive less new work than one that has already completed its assignments.

Design a LeastRequestsBalancer class:

  • LeastRequestsBalancer(int backendCount) creates backends 0 through backendCount - 1, each with zero active requests.
  • int acquire() selects the backend with the fewest active requests, increments its count, and returns its index.
  • void release(int backend) marks one request on backend complete by decrementing its count. A count must never fall below zero.

When several backends have the same minimum count, acquire() must select the smallest index. Request completions may arrive in any order.

Example 1:

Input:

Output:

Explanation: The first three requests produce counts [1,1,1]. The fourth goes to index 0, producing [2,1,1]. After backend 1 releases a request, its count is 0, so it receives the next request.

Example 2:

Input:

Output:

Explanation: Releasing backend 0 more times than it has active requests leaves its count at zero rather than making it negative.

Constraints

  • 1 <= backendCount <= 10^5
  • 0 <= backend < backendCount
  • At most 10^5 total calls are made to acquire and release.
  • A release on an idle backend is valid and leaves its count at 0.
Hints

Loading...
CallReturns
new LeastRequestsBalancer(3)null
acquire()0
acquire()1
acquire()2
acquire()0
release(1)null
acquire()1

The first three requests spread across all backends. The fourth returns to backend 0; releasing backend 1 makes it uniquely least loaded for the next request.

Run checks these cases. Submit also runs a larger hidden set.