dota2 Senate


649. Dota2 Senate – LeetCode


Problem Statement

In the Dota2 world, there are two parties: Radiant ('R') and Dire ('D'). The senate consists of n senators from these two parties, and the game is played in rounds.

Each round, in order:

Return the winning party as a string:


Examples

Example 1:

Input: senate = "RD"
Output: "Radiant"
Explanation:
R acts first and bans D → only R remains

Example 2:

Input: senate = "RDD"
Output: "Dire"
Explanation:
R bans D → D remains → D bans R → only D remains

Constraints


Intuition

This problem is essentially a turn-based simulation. The key observation is:


Approach: Queue-Based Round Simulation

  1. Initialize two queues:

    • rQ: Indices of Radiant senators.

    • dQ: Indices of Dire senators.

  2. Traverse senate and fill rQ and dQ with respective indices.

  3. While both queues are non-empty:

    • Pop the front senator from each queue.

    • Compare their indices.

    • The one with the lower index bans the other and is added back to its queue with index +n.

  4. When one queue is empty, the other party is the winner.


Java Code

class Solution {
    public String predictPartyVictory(String senate) {
        Queue<Integer> rQ = new LinkedList<>();
        Queue<Integer> dQ = new LinkedList<>();
        int n = senate.length();

        for (int i = 0; i < n; i++) {
            if (senate.charAt(i) == 'R') {
                rQ.add(i);
            } else {
                dQ.add(i);
            }
        }

        while (!rQ.isEmpty() && !dQ.isEmpty()) {
            int ri = rQ.poll();
            int di = dQ.poll();
            if (ri < di) {
                rQ.add(ri + n);
            } else {
                dQ.add(di + n);
            }
        }

        return rQ.size() > dQ.size() ? "Radiant" : "Dire";
    }
}

Time and Space Complexity

Metric Value
Time Complexity O(n) per round, worst-case O(n log n) total
Space Complexity O(n)
Explanation Each senator is added/removed from queue log(n) times

Dry Run

Input:

senate = "RDD"

Initial Queues:

Round Simulation:

Winner: Dire


Conclusion

This is a queue-based turn simulation problem that requires careful management of indices and round progression. It teaches: