Data Structures & AlgorithmsVery hardProduct company OA

Problem: A council of two parties, R and D, votes in rounds in seat order. On their turn a member bans the next opposing member who has not yet acted (and still has a voice); the banned member never acts again. The party that remains wins. Simulate with two queues of seat indices.

Problem: A council of two parties, R and D, votes in rounds in seat order. On their turn a member bans the next opposing member who has not yet acted (and still has a voice); the banned member never acts again. The party that remains wins. Simulate with two queues of seat indices.
from collections import deque
def council(s):
    r = deque(i for i, c in enumerate(s) if c == "R")
    d = deque(i for i, c in enumerate(s) if c == "D")
    n = len(s)
    while r and d:
        a, b = r.popleft(), d.popleft()
        if a < b: r.append(a + n)
        else: d.append(b + n)
    return "R" if r else "D"
print(council("RDD"), council("DRRDR"), council("DDRRR"))
What is printed?
  1. A. D R D
  2. B. R R D
  3. C. D D D
  4. D. D R R

Correct answer: A. D R D

Compare the earliest member of each party: whoever acts first bans the other and re-joins for the next round with index + n. "RDD": R0 bans D1, but D2 acts before R's next turn (index 3) and bans R → D. "DRRDR" → R. "DDRRR": D0 bans R2, D1 bans R3, R4 bans D5 (= D0's next turn), then D6 (D1) bans R9 → D. Majority alone does not decide it (R has 3 of 5 in "DDRRR"). O(n) rounds overall.

More Coding Interview Problems questions

Exams that ask this topic