Find a special person using knows(a,b)
HubSpotSoftware Engineer · OnsiteLast updated
This question evaluates algorithmic reasoning about pairwise relation inference using an oracle-style knows(a, b) API and the ability to minimize API calls, testing skills in graph modeling and asymptotic analysis.
Problem
You are given n people labeled 0 to n-1 at a party. You can call an API:
knows(a, b) -> bool: returnstrueif personaknows personb, otherwisefalse.
A special person is defined as someone who:
- Is known by everyone else (for all
i != x,knows(i, x) == true), and - Knows nobody else (for all
i != x,knows(x, i) == false).
Return the label of the special person if one exists, otherwise return -1.
Constraints
1 <= n <= 10^4- You should minimize the number of API calls; aim for O(n) calls.
Notes
knows(a, a)is undefined and should not be relied upon.
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.