Feature #5: Eligible Candidates

Implementing the "Eligible Candidates" feature for our "Cyber Security" project.

Description

We have n machines that are part of a cluster. We need to elect a leader. Leader election amongst all n machines would generate a lot of traffic and take a lot of time.

To optimize traffic and time, we have come up with a scheme that will reduce search space. Each machine is assigned a unique identifier, which is placed in a sorted array. A random number is picked, and k machines with IDs closest to the randomly drawn number are eligible candidates for leadership. Once the k machines are identified, the leader election from amongst these will take place.

Given a sorted integer array Servers, a randomly picked number num, and an integer k, your task is to find k machines with IDs closest to the random number. The IDs of the machines should also be sorted in ascending order.

An ID a is closer to num than an ID b, if |a - num| < |b - num|. In case |a - num| == |b - num|, then a is closer to num if a < b.

Note: The Servers array is sorted in ascending order and 1 <= k <= len(Servers).

The following examples may clarify these requirements:

Level up your interview prep. Join Educative to access 80+ hands-on prep courses.