Problem solution · C++

Find Servers That Handled Most Number of Requests

Find Servers That Handled Most Number of Requests: a C++ solution using binary search. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Binary search
Source
walkccc LeetCode Solutions
Length
44 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Binary search

For Find Servers That Handled Most Number of Requests, the implementation exploits a monotonic condition to discard half of the remaining search space after every check.

  1. Identify the ordered answer range or sorted search domain.
  2. Write a predicate whose truth changes only once.
  3. Move the appropriate boundary after each midpoint check and return the final feasible position.

Code notes

  • 44 lines of C++ from the credited upstream file 1606.cpp.
  • The implementation visibly relies on sequence storage, ordered lookup, work queue.
  • 4 loop blocks detected.

Complexity

Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeFind Servers That Handled Most Number of Requests · C++C++
Use this to learn the idea, then write your own version.
class Solution { public:  vector<int> busiestServers(int k, vector<int>& arrival, vector<int>& load) {    vector<int> ans;    vector<int> times(k);    set<int> idleServers;    // (endTime, server)    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> minHeap;     for (int i = 0; i < k; ++i)      idleServers.insert(i);     for (int i = 0; i < arrival.size(); ++i) {      // Pop all the servers that are available now.      while (!minHeap.empty() && minHeap.top().first <= arrival[i]) {        idleServers.insert(minHeap.top().second);        minHeap.pop();      }      // Get the next available server.      const int server = getNextAvailableServer(idleServers, i, k);      if (server == -1)        continue;      ++times[server];      minHeap.emplace(arrival[i] + load[i], server);      idleServers.erase(server);    }     const int busiest = ranges::max(times);    for (int i = 0; i < k; ++i)      if (times[i] == busiest)        ans.push_back(i);    return ans;  }  private:  int getNextAvailableServer(const set<int>& idleServers, int ithRequest,                             int k) {    if (idleServers.empty())      return -1;    const auto it = idleServers.lower_bound(ithRequest % k);    return it == idleServers.cend() ? *idleServers.begin() : *it;  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗