Sponsored
Sponsored
We utilize two separate queues to maintain indices of Radiant and Dire senators. In each round, senators from both parties execute their rights and effect bans on their opponent. The process continues until one queue becomes empty, indicating that all senators from one party have been eliminated.
Time Complexity: O(n), where n is the length of the senate, since each senator is processed a finite number of times.
Space Complexity: O(n), for storing indices in queues.
1function predictPartyVictory(senate) {
2 const radiant = [];
3 const dire = [];
4
5 for (let i = 0; i < senate.length; i++) {
6 if (senate.charAt(i) == 'R') {
7 radiant.push(i);
8 } else {
9 dire.push(i);
10 }
11 }
12
13 const n = senate.length;
14 while (radiant.length > 0 && dire.length > 0) {
15 const rIdx = radiant.shift();
16 const dIdx = dire.shift();
17 if (rIdx < dIdx) {
18 radiant.push(rIdx + n);
19 } else {
20 dire.push(dIdx + n);
21 }
22 }
23
24 return radiant.length > 0 ? "Radiant" : "Dire";
25}
26
Using JavaScript arrays to simulate queues, this approach processes each senator according to their party. We use the shift and push array operations to implement queue functionality and simulate the voting competition until one party is eliminated.