Dota2 Senate
Problem
Given a string representing senators from two parties ('R' for Radiant and 'D' for Dire), simulate the banning process where each senator can ban one opposing senator in a round-robin fashion, and return the winning party once all senators of the other party are banned.
- 1 ≤ senate.length ≤ 10⁴
- senate consists only of characters 'R' and 'D'
Example
senate = "RDD""Dire"Initially, Radiant senator at index 0 and Dire senators at indices 1 and 2. The Radiant senator bans the Dire senator at index 1 (the next Dire senator). The Dire senator at index 2 then bans the Radiant senator at index 0. Now only Dire senators remain, so the winner is 'Dire'.
Approach
Straightforward Solution
A naive approach simulates each round by iterating over the senate string and removing banned senators, which is O(n^2) due to repeated removals and scanning, and is inefficient for large inputs.
Core Observation
The problem models a circular queue where senators take turns banning opponents. Each senator's turn depends on the relative order of the next available opponent. The key is to simulate the process efficiently without explicitly removing elements from the string.
Path to Optimal
The insight is to track the indices of Radiant and Dire senators separately in queues. At each turn, compare the front indices of both queues to determine which senator bans the other. The senator with the smaller index bans the opponent and is re-enqueued with an updated index offset by the senate length to simulate the circular order. This approach simulates the rounds in O(n) time by avoiding costly removals and directly managing turns via queues.
Optimal Approach
Use two queues to store indices of Radiant and Dire senators. In each iteration, dequeue one senator from each queue and compare their indices. The senator with the smaller index bans the other and is re-enqueued with their index incremented by the senate length to simulate the next round. Continue until one queue is empty, then return the corresponding party as the winner.
Time
O(n)
Each senator is enqueued and dequeued at most once per round, and the total number of rounds is bounded by the number of senators, resulting in linear time complexity.
Space
O(n)
Two queues store indices of senators from each party, each potentially holding up to n elements, leading to O(n) auxiliary space.
Pattern Spotlight
Simulation (Queue-Based Round-Robin)
When simulating circular turn-based processes with elimination, maintain separate queues for competing groups and use index offsets to simulate rounds efficiently without costly removals.
Solution
| 1 | from collections import deque |
| 2 | |
| 3 | class Solution: |
| 4 | def predictPartyVictory(self, senate: str) -> str: |
| 5 | radiant = deque() |
| 6 | dire = deque() |
| 7 | n = len(senate) |
| 8 | |
| 9 | for i, senator in enumerate(senate): |
| 10 | if senator == "R": |
| 11 | radiant.append(i) |
| 12 | else: |
| 13 | dire.append(i) |
| 14 | |
| 15 | while radiant and dire: |
| 16 | r = radiant.popleft() |
| 17 | d = dire.popleft() |
| 18 | |
| 19 | if r < d: |
| 20 | radiant.append(r + n) |
| 21 | else: |
| 22 | dire.append(d + n) |
| 23 | |
| 24 | return "Radiant" if radiant else "Dire" |
Step-by-Step Solution
Separate Senators into Radiant and Dire Queues by Index
| 5 | radiant = deque() |
| 6 | dire = deque() |
| 7 | n = len(senate) |
| 9 | for i, senator in enumerate(senate): |
| 10 | if senator == "R": |
| 11 | radiant.append(i) |
| 12 | else: |
| 13 | dire.append(i) |
Objective
To initialize two queues that track the positions of Radiant and Dire senators for efficient turn simulation.
Key Insight
By storing the indices of each party's senators separately, the algorithm can simulate the banning process by comparing their order of turns directly. This avoids costly string modifications and allows efficient O(1) access to the next senator of each party.
Interview Quick-Check
Core Logic
Using two queues to track indices enables direct comparison of which senator acts first in each round.
State & Boundaries
The initial population of queues must reflect the original order of senators to preserve turn sequence.
Common Pitfalls & Bugs
Failing to separate senators by party or mixing indices would prevent correct simulation of turn order.
Simulate Banning Rounds by Comparing Front Senators and Re-Enqueuing Winners
| 15 | while radiant and dire: |
| 16 | r = radiant.popleft() |
| 17 | d = dire.popleft() |
| 19 | if r < d: |
| 20 | radiant.append(r + n) |
| 21 | else: |
| 22 | dire.append(d + n) |
Objective
To simulate the banning process by repeatedly comparing the next Radiant and Dire senators and updating their turn order.
Key Insight
At each step, the senator with the smaller index bans the opponent and is re-enqueued with their index incremented by the senate length to simulate the circular queue. This approach efficiently models the round-robin banning without modifying the original string or removing elements, ensuring linear time complexity.
Interview Quick-Check
Core Logic
Comparing the front indices of both queues determines which senator bans the other, and re-enqueuing the winner with an offset simulates the circular turn order.
State & Boundaries
The loop continues until one party's queue is empty, indicating all opposing senators have been banned.
Common Pitfalls & Bugs
Not updating the index by adding the senate length would fail to simulate the circular nature, causing incorrect turn ordering.
Return the Winning Party Based on Remaining Senators
| 24 | return "Radiant" if radiant else "Dire" |
Objective
To determine and return the winning party after all opposing senators have been banned.
Key Insight
Once one queue is empty, the other party has no opponents left and is declared the winner. This final check is a simple but essential step to conclude the simulation.
Interview Quick-Check
Core Logic
The presence of senators in one queue and absence in the other directly indicates the winning party.
Line Analysis
This solution has 5 Critical lines interviewers watch for.
return "Radiant" if radiant else "Dire"
Return the winning party based on which queue still contains senators.
The party with remaining senators after the banning process is the winner, so returning the corresponding name concludes the simulation.
while radiant and dire:
Continue simulation while both Radiant and Dire queues have senators.
The banning process continues until one party has no remaining senators, which is the termination condition.
if r < d:
Compare indices to determine which senator acts first.
The senator with the smaller index acts first and bans the opponent, reflecting the original turn order in the circular senate.
radiant.append(r + n)
Re-enqueue the Radiant senator with an updated index after banning the Dire senator.
Adding the senate length to the index simulates the Radiant senator's next turn in the circular order, preserving correct turn sequence.
dire.append(d + n)
Re-enqueue the Dire senator with an updated index after banning the Radiant senator.
Adding the senate length to the index simulates the Dire senator's next turn, maintaining the circular turn order.
radiant.append(i)
Append the index of a Radiant senator to the Radiant queue.
Storing indices in the Radiant queue maintains the order of Radiant senators for simulation.
dire.append(i)
Append the index of a Dire senator to the Dire queue.
Storing indices in the Dire queue preserves the order of Dire senators for turn-based simulation.
r = radiant.popleft()
Dequeue the next Radiant senator's index.
Retrieving the next Radiant senator simulates their turn in the banning process.
d = dire.popleft()
Dequeue the next Dire senator's index.
Retrieving the next Dire senator simulates their turn in the banning process.
else:
Handle the case where the Dire senator acts first and bans the Radiant senator.
Ensures the correct senator is banned and the winner is re-enqueued properly to continue the simulation.
radiant = deque()
Initialize a queue to store indices of Radiant senators.
This queue will track Radiant senators' turn order, enabling efficient simulation of their banning actions.
dire = deque()
Initialize a queue to store indices of Dire senators.
This queue will track Dire senators' turn order, allowing direct comparison with Radiant senators during simulation.
if senator == "R":
Check if the current senator belongs to the Radiant party.
Identifying party membership allows correct placement into the corresponding queue for turn tracking.
else:
Handle the case where the senator belongs to the Dire party.
Ensures all Dire senators are correctly identified and processed separately from Radiant senators.
n = len(senate)
Store the length of the senate string.
The length is used to calculate the next turn index for senators re-enqueued after banning opponents, simulating circular order.
for i, senator in enumerate(senate):
Iterate over each senator and their index in the senate string.
Enumerating senators with their indices preserves the original order, which is critical for simulating turn sequence.
Test Your Understanding
Why does re-enqueuing the winning senator with an index offset by the senate length correctly simulate the circular order of turns?
Because adding the senate length to the index places the senator's next turn after all current senators have had their turn, effectively simulating the circular rotation without modifying the original order.
Related Problems
Simulation pattern
Don't just read it. Drill it.
Reconstruct Dota2 Senate from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.
Unlock the Dota2 Senate drill