문제
The observer pattern lets objects subscribe to a subject and get notified whenever something happens. Here, people subscribe to topics and every published event goes to everyone subscribed to its topic.
Each subscription is <person> <topic>. A repeated subscription has no extra effect. Then each event in events is a topic name: every subscriber of that topic receives one notification. Events on topics nobody follows are dropped.
Implement event_subscribers(subscriptions, events).
Input
subscriptions: "<person> <topic>" strings (names have no spaces).
events: Topic names, in publishing order.
Output
Return "<person>:<count>" for every person who has at least one subscription, sorted by name (ordinal character order).
제약 조건
1 ≤ number of subscriptions ≤ 10,000
0 ≤ number of events ≤ 100,000
예시
입력:
events = ["news", "sports", "weather"]
subscriptions = ["bob sports", "alice news", "alice sports"]
예상 출력:
expected = ["alice:2", "bob:1"]
입력:
std::vector<std::string> events = {"news", "sports", "weather"};
std::vector<std::string> subscriptions = {"bob sports", "alice news", "alice sports"};
예상 출력:
std::vector<std::string> expected = {"alice:2", "bob:1"};
입력:
string[] events = new string[] {"news", "sports", "weather"};
string[] subscriptions = new string[] {"bob sports", "alice news", "alice sports"};
예상 출력:
string[] expected = new string[] {"alice:2", "bob:1"};
설명
alice follows news and sports, so she gets both events; bob only gets sports; nobody follows weather: ["alice:2", "bob:1"].
입력:
events = []
subscriptions = ["zoe tech", "zoe tech"]
예상 출력:
expected = ["zoe:0"]
입력:
std::vector<std::string> events = {};
std::vector<std::string> subscriptions = {"zoe tech", "zoe tech"};
예상 출력:
std::vector<std::string> expected = {"zoe:0"};
입력:
string[] events = new string[] {};
string[] subscriptions = new string[] {"zoe tech", "zoe tech"};
예상 출력:
string[] expected = new string[] {"zoe:0"};
설명
The repeated subscription counts once, and no events were published: ["zoe:0"].
접근 방법
먼저 스스로 풀어 본 뒤 힌트를 하나씩 열어 보세요.
힌트 1
Group subscribers by topic so each event finds its audience quickly.
힌트 2
Use a set per topic so a repeated subscription counts once.
힌트 3
Everyone who subscribed appears in the result, even with zero notifications.
예상 복잡도
O(subscriptions + events × subscribers per topic) time, O(subscriptions) extra space
참고 자료
이 문제는 CodeUtility에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.