Python 0649.py
class Solution:
def predictPartyVictory(self, senate: str) -> str:
r = []
d = []
for i in range(len(senate)):
if senate[i] == "D":
d.append(i)
else:
r.append(i)
tick = len(senate)
while True:
if not d:
return "Radiant"
if not r:
return "Dire"
if d[0] < r[0]:
d.append(tick)
else:
r.append(tick)
del d[0] # one voted (and added to the end of the queue), the other was banned
del r[0]
tick += 1
Difficulty
and has an acceptance rate of about 50% (600k+ submissions).
Typical patterns to solve this problem:
- Greedy
- Queue
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the “Dota2 Senate” problem by simulating the voting process with two queues that store the positions of the remaining Radiant and Dire senators. The algorithm repeatedly determines which party’s senator gets to act first, bans the opponent’s next senator, and re-queues the acting senator for a future round. The simulation continues until one of the queues becomes empty, at which point the surviving party is declared the winner.
Initialization of Party Queues
r = []
d = []
for i in range(len(senate)):
if senate[i] == "D":
d.append(i)
else:
r.append(i)
During the first pass over the input string, the code separates the indices of Radiant (r) and Dire (d) senators. By storing the original positions, the algorithm can later compare which senator would act earlier in the current round.
Round Counter
tick = len(senate)
tick represents the next virtual index that will be assigned to a senator who survives a round and is placed at the end of its queue. Starting it at the length of the original senate ensures that newly generated indices are larger than any original position, preserving the chronological order of future actions.
Main Simulation Loop
while True:
if not d:
return "Radiant"
if not r:
return "Dire"
At the beginning of each iteration the code checks whether one of the queues is empty. If the Dire queue is empty, all remaining senators are Radiant, so the function returns "Radiant". Conversely, an empty Radiant queue leads to a "Dire" victory. These early exits handle edge cases where the input contains senators from only one party or where the simulation has already eliminated one side.
Determining the Acting Senator
if d[0] < r[0]:
d.append(tick)
else:
r.append(tick)
The first elements of the queues (d[0] and r[0]) hold the earliest-acting Dire and Radiant senators, respectively. By comparing these indices, the algorithm decides which party’s senator gets to act first in the current round. The winner’s index is appended to the end of its own queue with the current tick value, representing that the senator will participate again after all existing senators have taken their turns.
Banning the Opponent
del d[0] # one voted (and added to the end of the queue), the other was banned
del r[0]
Regardless of which party acted, the code removes the first element from both queues. The element removed from the winning party has already been re-queued with a new index, while the element removed from the losing party represents the banned senator. This simultaneous deletion ensures that exactly one senator is eliminated per round.
Advancing the Virtual Index
tick += 1
After processing a round, tick is incremented so that the next surviving senator receives a unique, larger index. This monotonic increase guarantees that the order of future actions respects the original sequence of rounds.
Edge Cases Handled
When the input string is empty, both r and d remain empty after initialization. The first condition if not d: evaluates to true, causing the function to return "Radiant" immediately. This behavior defines a deterministic outcome for an empty senate.
If the input consists solely of Radiant or solely of Dire senators, the corresponding queue is populated while the opposite queue stays empty. The early-exit checks in the main loop detect this situation before any iteration of the voting simulation, returning the correct winner without unnecessary processing.
The comparison d[0] < r[0] also correctly handles cases where the first Radiant and Dire senators have the same index, which cannot occur because each position belongs to exactly one party. Nevertheless, the logic is robust against any ordering of indices, ensuring that the party with the earlier index always wins the round.
Performance Optimizations
The algorithm uses plain Python lists as queues, avoiding the overhead of more complex data structures. Appending to the end of a list is an amortized constant-time operation, and the use of a single integer (tick) to generate new positions eliminates the need for additional objects or look-ups. By re-using the same list objects throughout the simulation, the code minimizes memory allocations and keeps the runtime footprint low. The early-exit checks prevent unnecessary iterations when a decisive outcome is already known, allowing the function to terminate as soon as one party is eliminated.
ELI5 - Simplified Explanation
Imagine a big room filled with two teams of people who are trying to make a choice. One team wears red shirts and the other team wears blue shirts. To keep track of everyone, the code starts by sorting all the red team members into one line and all the blue team members into another line. Each person has a special number that shows where they are standing in the room.
The process happens in a big circle. When it is time for a turn, the person at the front of each line looks at the other line. The person who is standing in a better spot gets to stay, and they ban the person on the other team who is standing in the very next spot. Once a person from a team uses their turn to ban someone, they go to the very back of their line to wait for another turn later.
As the game continues, the people who were banned have to leave the room. This keeps going until one whole team is gone. When there are no people left on the blue team, the red team wins. When there are no people left on the red team, the blue team wins. Every time someone takes a turn, the count of the total spots keeps going up so everyone knows exactly when it is their turn to move to the back of the line.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||
| WalkCCC | C++ | ||||||||
| leetcode.ca | C++ | Java | Rust | Python | Go | TS | |||
| LeetcodeHelp | C++ | Java | Python | ||||||
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| JoshCrozier | JS | ||||||||
| linouk23 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| vthwang | Java | ||||||||
| wisdompeak | C++ | ||||||||
| zfang399 | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++ | ||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| JoshCrozier | JavaScript | ||||||||
| linouk23 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| vthwang | Java | ||||||||
| wisdompeak | C++ | ||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 495: Teemo Attacking
Solved On The Same Day
- problem 724: Find Pivot Index
- problem 872: Leaf-Similar Trees
- problem 933: Number of Recent Calls
- problem 1207: Unique Number of Occurrences
- problem 1732: Find the Highest Altitude
- problem 2215: Find the Difference of Two Arrays
- problem 328: Odd Even Linked List
- problem 443: String Compression
- problem 735: Asteroid Collision
- problem 875: Koko Eating Bananas
- problem 901: Online Stock Span
- problem 1161: Maximum Level Sum of a Binary Tree
- problem 1268: Search Suggestions System
- problem 1282: Group the People Given the Group Size They Belong To
- problem 1372: Longest ZigZag Path in a Binary Tree
- problem 1448: Count Good Nodes in Binary Tree
- problem 1456: Maximum Number of Vowels in a Substring of Given Length
- problem 1493: Longest Subarray of 1's After Deleting One Element
- problem 1647: Minimum Deletions to Make Character Frequencies Unique
- problem 1657: Determine if Two Strings Are Close
- problem 1926: Nearest Exit from Entrance in Maze
- problem 2095: Delete the Middle Node of a Linked List
- problem 2130: Maximum Twin Sum of a Linked List
- problem 2352: Equal Row and Column Pairs
- problem 2390: Removing Stars From a String
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality