Skip to the code
cf.
+10 XP

#405 Find the Gateway Service

easy

A team draws its services as n nodes numbered 0 to n - 1, with links[i] = [a, b] meaning services a and b talk to each other (both ways).

A gateway is a service that is linked directly to every other service. Write findGateway(n, links) that returns the gateway's number, or -1 if there isn't one. If more than one service qualifies, return the smallest number.

No link appears twice and no service links to itself.

Example 1

Input: n = 4, links = [[0,1],[1,2],[1,3]]
Output: 1

Service 1 is linked to 0, 2, and 3: all three other services.

Example 2

Input: n = 4, links = [[0,1],[1,2],[2,3]]
Output: -1

Every service is missing a link to at least one other service.

Constraints

  • 2 <= n <= 10000
  • 0 <= links.length <= 50000
  • 0 <= a, b < n and a !== b
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).