|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + string predictPartyVictory(string senate) { |
| 4 | + // Queues to store the indices of each senator from Radiant (R) and Dire (D) |
| 5 | + queue<int> rad, dir; |
| 6 | + |
| 7 | + // Get the total number of senators |
| 8 | + int n = senate.length(); |
| 9 | + |
| 10 | + // Loop through the senate string to separate Radiant and Dire senators into different queues |
| 11 | + for (int i = 0; i < n; i++) { |
| 12 | + if (senate[i] == 'R') { |
| 13 | + // If senator belongs to Radiant party, add their index to rad queue |
| 14 | + rad.push(i); |
| 15 | + } else { |
| 16 | + // If senator belongs to Dire party, add their index to dir queue |
| 17 | + dir.push(i); |
| 18 | + } |
| 19 | + } |
| 20 | + |
| 21 | + // Diagram illustrating initial queue states: |
| 22 | + // Senate: "RRDD" |
| 23 | + // Radiant Queue (R): [0, 1] |
| 24 | + // Dire Queue (D): [2, 3] |
| 25 | + |
| 26 | + /* |
| 27 | + Initial queue states: |
| 28 | + Radiant Queue (R): [0, 3] |
| 29 | + Dire Queue (D): [1, 2] |
| 30 | +
|
| 31 | + Step 1: |
| 32 | + R0 vs D1: R0 bans D1 |
| 33 | + Radiant Queue (R): [3, 4] |
| 34 | + Dire Queue (D): [2] |
| 35 | +
|
| 36 | + Step 2: |
| 37 | + R3 vs D2: D2 bans R3 |
| 38 | + Radiant Queue (R): [4] |
| 39 | + Dire Queue (D): [] |
| 40 | +
|
| 41 | + Final state: |
| 42 | + Winner: Radiant |
| 43 | + */ |
| 44 | + |
| 45 | + // Process the queues while both parties still have senators left |
| 46 | + while (!rad.empty() && !dir.empty()) { |
| 47 | + // Compare the front senators from each party |
| 48 | + if (rad.front() < dir.front()) { |
| 49 | + // If the Radiant senator appears before the Dire senator, ban the Dire senator |
| 50 | + // Push the Radiant senator to the back of the queue with updated index (n++) |
| 51 | + rad.push(n++); |
| 52 | + } else { |
| 53 | + // Otherwise, the Dire senator bans the Radiant senator and pushes itself to the back |
| 54 | + dir.push(n++); |
| 55 | + } |
| 56 | + // Remove the processed senators from the front of their respective queues |
| 57 | + rad.pop(); |
| 58 | + dir.pop(); |
| 59 | + } |
| 60 | + |
| 61 | + // Return the winning party based on which queue is not empty |
| 62 | + return (rad.empty()) ? ("Dire") : ("Radiant"); |
| 63 | + } |
| 64 | +}; |
0 commit comments