Event Subscriptions (Topic Bus)
Programming Interview
Hard
10 views
Problem Description
Commands: SUB user topic, UNSUB user topic, PUB topic msg(no spaces). For each PUB print how many users receive the message.
Input Format
See description.
Output Format
See description.
Sample Test Case
Input:
6
SUB u1 sports
SUB u2 sports
SUB u1 tech
PUB sports hi
UNSUB u2 sports
PUB sports yo
Constraints
Total operations up to 200000.
Official Solution
import sys
lines=sys.stdin.read().splitlines()
if not lines or not lines[0].strip():
sys.exit(0)
q=int(lines[0].strip())
subs={}
out=[]
for i in range(1,1+q):
parts=(lines[i] if i < len(lines) else '').split()
if not parts:
continue
cmd=parts[0]
if cmd=='SUB':
u=parts[1]; t=parts[2]
subs.setdefault(t,set()).add(u)
elif cmd=='UNSUB':
u=parts[1]; t=parts[2]
if t in subs:
subs[t].discard(u)
else:
t=parts[1]
out.append(str(len(subs.get(t,set()))))
sys.stdout.write('\
'.join(out))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!