649. Dota2 Senate
Problem
Senators from two parties, 'R' (Radiant) and 'D' (Dire), act in the order of the string, round after round. On their turn, a senator still in play either removes one opposing senator's rights for good or, if only their own party is left, declares victory. Assuming everyone plays optimally, return "Radiant" or "Dire".
Example: "RD" → "Radiant"; "RDD" → "Dire"
Constraints: length ≤ 10⁴.
Two queues of senator indices. The earlier senator bans the other; the winner re-enters with index + n (next round).
Complexity: O(n).
class Solution:
def predictPartyVictory(self, senate: str) -> str:
n = len(senate)
r = deque(i for i, c in enumerate(senate) if c == "R")
d = deque(i for i, c in enumerate(senate) if c == "D")
while r and d:
a, b = r.popleft(), d.popleft()
if a < b:
r.append(a + n)
else:
d.append(b + n)
return "Radiant" if r else "Dire"
assert Solution().predictPartyVictory("RD") == "Radiant"
assert Solution().predictPartyVictory("RDD") == "Dire"
class Solution {
public String predictPartyVictory(String senate) {
int n = senate.length();
Deque<Integer> r = new ArrayDeque<>(), d = new ArrayDeque<>();
for (int i = 0; i < n; i++) (senate.charAt(i) == 'R' ? r : d).add(i);
while (!r.isEmpty() && !d.isEmpty()) {
int a = r.poll(), b = d.poll();
if (a < b) r.add(a + n); else d.add(b + n);
}
return r.isEmpty() ? "Dire" : "Radiant";
}
}
func predictPartyVictory(senate string) string {
n := len(senate)
r, d := []int{}, []int{} // turn indices of each party's active senators
for i := 0; i < n; i++ {
if senate[i] == 'R' {
r = append(r, i)
} else {
d = append(d, i)
}
}
for len(r) > 0 && len(d) > 0 {
a, b := r[0], d[0]
r, d = r[1:], d[1:]
if a < b { // the earlier senator bans the other and votes again next round
r = append(r, a+n)
} else {
d = append(d, b+n)
}
}
if len(r) > 0 {
return "Radiant"
}
return "Dire"
}