Problem 649

Abstract / Summary

In a game where senators cast bans in turns, determine which party ultimately outlasts the other by simulating their ban actions.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
26 lines | 671 bytes | submitted September 12, 2023 | GitHub   4% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 50% (600k+ submissions).

Typical patterns to solve this problem:
  • Greedy
  • Queue
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 6.77 | σ = 1.05

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
29 links | 17 authors | 8 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

26 solutions   September 12, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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