Chat app~30 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-649queues
A group chat votes on a plan. Every member belongs to team A or team B, and members speak in the order they appear in the member list. The vote goes in rounds, and each round every member who is still in the chat speaks once, in order.
A speaker removes the next member of the other team. That is the first opponent still in the chat after their position, going round to the top of the list if needed. A removed member loses their turn. When a team has no members left, the other team wins.
Write winning_team(votes).
votes[i] is "A" or "B", the team of the member at position i."A" or "B": the team that has members left when the other team has none.Input: votes = "AABBB"
Output: "A"Keep two queues of positions, one for each team. The front of each queue is the next member of that team to speak. The member with the smaller position speaks first, and removes the front of the other queue. The speaker joins the back of their queue with n added to the position, to speak again in the next round, after everyone in this round.
| Speakers (A, B) | Who speaks first | Result | Team A queue | Team B queue |
|---|---|---|---|---|
| start | 0, 1 | 2, 3, 4 | ||
| 0 and 2 | A (0 before 2) | A removes B at 2 and rejoins as 5 | 1, 5 | 3, 4 |
| 1 and 3 | A (1 before 3) | A removes B at 3 and rejoins as 6 | 5, 6 | 4 |
| 5 and 4 | B (4 before 5) | B removes A at 5 and rejoins as 9 | 6 | 9 |
| 6 and 9 | A (6 before 9) | A removes B at 9 and rejoins as 11 | 11 | empty |
Team B has no members left, so team A wins.
Input: votes = "AB"
Output: "A"Member 0 speaks first and removes the only member of team B.
Input: votes = "BBAAA"
Output: "B"Team A has more members, but team B speaks first. In round 1 the two B members remove the A members at 2 and 3, and the A at 4 removes the B at 0. In round 2 the B at 1 removes the A at 4.
1 ≤ length of votes ≤ 2 × 10^5votes has only the letters A and BActing out each removal by scanning round the list for the next opponent can cross half the list. For two blocks of 100,000 members, each speaker scans about 100,000 positions, which is about 10^10 steps.
A queue for each team gives the next speaker of each team in O(1). Each step removes one member, so there are at most n - 1 steps, and the whole simulation is O(n).