The Dota2 senate consists of senators representing two parties: the Radiant and the Dire. The senators sit in a row and each senator can either ban one senator of the opposite party or announce victory if all the others are banned.
Given a string senate
consisting of characters ‘R’ and ‘D’ representing Radiant and Dire senators respectively, write a solution to predict which party will announce the victory. The output should be either ‘Radiant’ or ‘Dire’.
This ensures that we simulate the banning process correctly as per their positions in the senate string.
#include <iostream>
#include <queue>
#include <string>
std::string predictPartyVictory(std::string senate) {
std::queue<int> radiant, dire;
int n = senate.size();
// Populate the queues with the initial positions of 'R' and 'D'
for (int i = 0; i < n; ++i) {
if (senate[i] == 'R') {
radiant.push(i);
} else { // senate[i] == 'D'
dire.push(i);
}
}
// Process banning in rounds
while (!radiant.empty() && !dire.empty()) {
int rIndex = radiant.front();
int dIndex = dire.front();
radiant.pop();
dire.pop();
// The one with the smaller index bans the other
if (rIndex < dIndex) {
radiant.push(rIndex + n); // Radiant bans Dire and returns in next round
} else {
dire.push(dIndex + n); // Dire bans Radiant and returns in next round
}
}
// Determine the winner
return radiant.empty() ? "Dire" : "Radiant";
}
int main() {
std::string senate = "RDD";
std::cout << predictPartyVictory(senate) << std::endl; // Output should be "Dire"
return 0;
}
n
steps. So, in the worst case scenario, a senator will be processed in 2*n
iterations.Hence, the overall time complexity is O(n), where n
is the length of the senate string. This is efficient and should handle the upper constraint of 10,000 efficiently.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?