Find spammer with minimal hasMessaged calls
Company: HubSpot
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Onsite
Quick Answer: 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.
Constraints
- 0 <= n <= 10^4 where n = len(matrix); matrix is n x n.
- matrix[a][b] is 0 or 1; matrix[i][i] == 0 (no self-messages).
- At most one spammer exists.
- Must use O(n) lookups and O(1) extra space.
Examples
Input: [[0, 1, 1], [0, 0, 0], [0, 0, 0]]
Expected Output: 0
Explanation: Account 0 messaged 1 and 2 and received from no one -> spammer 0.
Input: [[0, 1, 1], [0, 0, 0], [0, 1, 0]]
Expected Output: 0
Explanation: Account 2 messaging 1 does not affect 0; 0 still messaged everyone and received from no one -> 0.
Input: [[0, 0, 0, 0], [1, 0, 1, 1], [0, 0, 0, 0], [0, 0, 0, 0]]
Expected Output: 1
Explanation: Account 1 messaged 0, 2, 3 and received from no one -> spammer 1 (survivor is not index 0).
Input: [[0, 1, 1], [1, 0, 1], [1, 1, 0]]
Expected Output: -1
Explanation: Everyone messaged everyone, so every account received a message -> no spammer.
Input: [[0, 1, 1, 1], [0, 0, 0, 0], [0, 0, 0, 0], [1, 0, 0, 0]]
Expected Output: -1
Explanation: Account 0 messaged everyone but account 3 messaged 0, so 0 received a message -> verification fails -> -1.
Input: [[0, 1, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
Expected Output: -1
Explanation: Account 0 did not message account 2 (matrix[0][2] == 0), so it missed an out-edge -> -1.
Input: [[0]]
Expected Output: 0
Explanation: Edge case n=1: a lone account vacuously messaged every OTHER account and received from none -> 0.
Input: []
Expected Output: -1
Explanation: Edge case n=0: no accounts exist -> -1.
Input: [[0, 0], [1, 0]]
Expected Output: 1
Explanation: Minimal n=2 case: account 1 messaged 0 and received nothing -> spammer 1.
Hints
- This is the classic 'celebrity problem' with the messaging direction inverted: a spammer SENDS to everyone and RECEIVES from no one (a celebrity is KNOWN by everyone and KNOWS no one).
- Key invariant: one lookup matrix[a][b] always eliminates exactly one of {a, b}, and the eliminated one is never the spammer. If 1, b received a message (out). If 0, a missed an out-edge (out).
- Phase 1 always produces a survivor even when no spammer exists, so a Phase-2 verification pass over all of the survivor's out-edges and in-edges is required to confirm or return -1.