KatInterview

Spot the VIP in a Social Network

Trees & GraphsAuto-graded · 18 test cases
MediumAuto-gradedTrees & Graphsgraphseliminationtwo-pass

Last updated

Tests whether a candidate can exploit a single elimination insight to find a universal acquaintance in O(n) time instead of O(n²).

Problem Statement

At a networking event with n attendees (numbered 0 through n-1), there may be a VIP: someone that every other attendee recognizes, but who recognizes nobody in return.

You are given a square grid acquainted of size n × n, where acquainted[i][j] == 1 means person i recognizes person j, and 0 means they do not.

Return the index of the VIP. If no such person exists, return -1.

A correct algorithm must do better than the brute-force O(n²) scan.

Constraints

  • 1 ≤ n ≤ 2000
  • acquainted[i][i] == 0 for all i (no one is listed as recognizing themselves)
  • acquainted is a list of lists of integers, each value either 0 or 1
  • There is at most one VIP (uniqueness is guaranteed by the definition)
  • A single attendee (n == 1) is trivially the VIP

Examples

Example 1

Input: find_vip([[0, 1, 0], [0, 0, 0], [0, 1, 0]])

Output: 1

Example 2

Input: find_vip([[0, 1], [1, 0]])

Output: -1

Example 3

Input: find_vip([[0]])

Output: 0

Hints

Hint 1

Each entry acquainted[i][j] lets you immediately rule out exactly one of the two people as the VIP — think about which one is eliminated in each case.

Hint 2

A single forward pass through all attendees can narrow the field down to one surviving candidate using only n-1 lookups total.

Hint 3

The survivor of the first pass is not yet confirmed. You still need to verify both directions — that they recognize nobody and that everybody recognizes them — before returning their index.