AlgoMaster Logo
AlgoMasterElect a Leader with the Bully Rulemedium

Elect a Leader with the Bully Rule

medium

In the bully election model, the live node with the greatest identifier becomes the leader. Failed nodes cannot participate, even when one has the greatest identifier in the cluster.

Design a BullyLeaderElector class:

  • BullyLeaderElector() creates a stateless elector.
  • int elect(int[] ids, int[] alive) returns the elected node ID.

ids[i] is the identifier of node i. alive[i] is 1 when that node is alive and 0 when it has failed. Return the greatest ID among live nodes, or -1 if every node has failed.

Example 1:

Input:

Output:

Explanation: ID 4 is the greatest cluster ID, but that node has failed. The greatest live ID is 3.

Example 2:

Input:

Output:

Explanation: No live node remains to become leader.

Constraints

  • 1 <= ids.length == alive.length <= 10^5
  • 0 <= ids[i] <= 10^9
  • alive[i] is either 0 or 1.
  • Node IDs do not need to be sorted or unique.
  • At most 100 calls are made to elect.
Hints

Loading...
CallReturns
new BullyLeaderElector()null
elect([3,1,4,2], [1,1,0,1])3

Node 4 has failed. Among IDs 3, 1, and 2 that remain alive, 3 is the greatest.

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