Find spammer with minimal hasMessaged calls
HubSpotSoftware Engineer · OnsiteLast updated
Find the "spammer" account that messaged every other account but received from none, using only a hasMessaged(a, b) oracle. This is the classic find-the-celebrity problem inverted, solved with a two-phase elimination-then-verify algorithm in O(n) oracle calls and O(1) extra space, with full correctness proof and edge-case handling.
Question
You have n accounts labeled 0..n-1 and an oracle API:
boolean hasMessaged(a, b) // true iff account a has sent at least one message to account b
Define a spammer as an account that has sent a message to every other account and has received messages from no other account. At most one such account can exist.
You may only call hasMessaged — you have no direct access to the underlying message graph.
- Core task. Implement
findSpammer(n)that returns the spammer's index if one exists, otherwise returns-1. - Minimize oracle calls. Achieve O(n) calls to
hasMessagedand O(1) extra space. State and justify the worst-case number of oracle calls. - Correctness. Explain why the algorithm is correct — in particular, why the elimination phase cannot discard the true spammer, and why the verification phase is necessary.
- Complexity. Analyze time complexity (in oracle calls) and extra-space complexity.
- Edge cases. Handle
nin{0, 1}, the possibility of multiple candidates surviving elimination, and self-messages (hasMessaged(i, i)).
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.