InterviewPrepKit

Home / Coding / Greedy

Dota2 Senate

medium Original ↗
Solving tips
  • Greedy insight: each senator should always ban the nearest UPCOMING opponent (the one acting soonest), since sparing them lets that opponent eliminate your ally first.
  • Model with two queues of turn indices (one per party); the smaller index acts first and bans the other queue's front senator, and the survivor re-queues at index+n to interleave laps.
  • Loop until one queue empties; each round permanently removes one senator so it's O(n) time, O(n) space.
  • Pitfall: majority does not decide it (position does), and you must re-queue the survivor with the +n offset or laps stop interleaving.

Problem

Two parties, Radiant ('R') and Dire ('D'), sit in a senate. You are given a string senate where each character is the party of one senator, listed in the order they will act. Voting happens in round-robin order, cycling through the survivors again and again.

When it is a senator’s turn, they may exercise one right: ban any one senator from the other party, removing that senator from all future rounds. (A rational senator always uses this right — passing never helps.) The process repeats, skipping banned senators, until every remaining senator belongs to one party. Return the winning party: "Radiant" or "Dire".

Because each senator plays optimally for their own party, the question is really: given the seating order, which party can guarantee the win?

Examples

  • senate = "RD""Radiant" — R acts first and bans D; only R remains.
  • senate = "RDD""Dire" — R bans one D. The remaining D (who has not acted yet this round) then bans R. Only D’s remain.
  • senate = "RRDDD""Radiant" — the two R’s act first each lap and pick off D’s faster than the three D’s can retaliate, despite being outnumbered.

Constraints

  • 1 <= len(senate) <= 10^4
  • senate contains only 'R' and 'D', and both letters appear at least once.

An O(n) or O(n log n) solution is expected; the number of ban rounds can be large, so naive re-scanning is too slow.

Think about it first

Hint 1 When a senator bans someone, whom should they pick? Banning a distant opponent leaves a nearer opponent free to act first. Which single opponent is the most urgent threat?
Hint 2 Order is everything: process senators by their turn index. Think of two queues of indices, one per party. Whoever has the smaller index acts first and eliminates the other's front senator.
Hint 3 A surviving senator gets to act again next lap. Model that by re-queuing them with index i + n, so laps interleave naturally. Loop until one queue empties.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.