#649

Dota2 Senate

Medium
StringGreedyQueueQueueGreedy
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a queue to efficiently manage the senators' actions. Each senator's index is stored, allowing us to process their actions in a round-robin fashion, ensuring we only process each senator once per round.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize two queues, one for each party (Radiant and Dire).
  2. 2Step 2: Enqueue the indices of senators based on their party.
  3. 3Step 3: Process senators in a loop: dequeue one from each party, the one with the smaller index bans the other.
  4. 4Step 4: Enqueue the winner back to their respective queue with an updated index.
solution.py18 lines
1from collections import deque
2
3def predictPartyVictory(senate):
4    radiant = deque()
5    dire = deque()
6    for i, s in enumerate(senate):
7        if s == 'R':
8            radiant.append(i)
9        else:
10            dire.append(i)
11    while radiant and dire:
12        r_index = radiant.popleft()
13        d_index = dire.popleft()
14        if r_index < d_index:
15            radiant.append(r_index + len(senate))
16        else:
17            dire.append(d_index + len(senate))
18    return 'Radiant' if radiant else 'Dire'

Complexity note: The time complexity is O(n) because each senator is processed once, and the space complexity is O(n) due to the storage of indices in the queues.

  • 1The order of senators matters greatly in determining the outcome.
  • 2Using queues allows us to efficiently manage the round-based voting process.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.