KatInterview

Locate the Universally Followed Silent Guest

Trees & GraphsAuto-graded · 20 test cases
EasyAuto-gradedTrees & Graphsgraphcelebrity-problemtwo-pass

Last updated

Find the one node in a directed relation that everyone points to and that points to nobody, using a linear elimination pass followed by verification.

Find the Universal Sink

A gathering has n guests labeled 0 through n-1. Acquaintance is directional: guest a may know guest b without b knowing a.

You receive the list acquaintances. Each entry [a, b] states that guest a knows guest b. Any ordered pair (a, b) that does not appear in the list means a does not know b.

A guest x is the focal guest if both of these hold:

  1. Every other guest knows x. For every i != x, the pair [i, x] is present.
  2. x knows no one. For every i != x, the pair [x, i] is absent.

Return the label of the focal guest, or -1 if there is none.

Rules and edge cases

  • At most one focal guest can exist, so the answer is unique.
  • If n == 1, guest 0 is trivially the focal guest, because there is nobody else to know or to be known by.
  • No entry has a == b. If the same pair appears more than once, it still states a single fact.
  • Entries are only about guests in the range 0..n-1.

Aim for a solution that does not examine all n * (n - 1) ordered pairs one by one. A linear number of relationship lookups is achievable.

Constraints

  • 1 <= n <= 10^4
  • Each entry of acquaintances is [a, b] with 0 <= a, b < n and a != b.
  • acquaintances may be empty.
  • Return an integer in [0, n-1], or -1.

Examples

Example 1

Input: find_focal_guest(3, [[0, 2], [1, 2]])

Output: 2

Example 2

Input: find_focal_guest(3, [[0, 1], [1, 2], [2, 0]])

Output: -1

Example 3

Input: find_focal_guest(1, [])

Output: 0

Hints

Hint 1

Pick any two different guests a and b and ask whether a knows b. Whichever answer you get, one of the two can be ruled out as the focal guest. Which one in each case?

Hint 2

Keep a running candidate. Compare it against each next guest: if the candidate knows that guest, the candidate is out and the new guest takes over; otherwise the new guest is out.

Hint 3

After the scan only one guest can possibly qualify, but nothing proves they do. Run a verification pass: everyone else must know them, and they must know no one.