KatInterview

Find the Hub Node in a Star-Shaped Network

Trees & GraphsAuto-graded · 17 test cases
MediumAuto-gradedTrees & Graphsgraphsdegreestar-graph

Last updated

Tests recognition of star-graph topology and the insight that the central node is uniquely identified by its degree.

Problem Statement

You are managing a fleet of n machines, each labeled from 0 to n-1. The machines are wired together in a star topology: one special machine — the hub — has a direct cable to every other machine. The remaining machines are leaf nodes and are only ever cabled to the hub; no two leaf nodes are directly connected to each other.

You receive the wiring plan as a list of undirected connections. Each entry connections[i] = [a, b] means machine a and machine b share a cable.

Given the number of machines n and the list connections, return the label of the hub machine.

Input

  • n — the total number of machines (integer).
  • connections — a list of pairs [a, b], each representing one undirected cable between machine a and machine b.

Output

Return the integer label of the hub machine.

Constraints

  • 3 <= n <= 10^5
  • connections.length == n - 1
  • All machine labels are distinct integers in the range [0, n-1].
  • The input always describes a valid star topology, so exactly one hub exists.

Examples

Example 1

Input: find_hub(4, [[0, 1], [0, 2], [0, 3]])

Output: 0

Example 2

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

Output: 2

Hints

Hint 1

Count how many cables are attached to each machine. What degree must the hub have, and what degree must every leaf have?

Hint 2

In a star with n nodes there are exactly n-1 edges, so the hub touches n-1 cables. Since n >= 3, no leaf can share that count — leaves always have degree 1.

Hint 3

If you trust the input to be a valid star, you only need the first two connections: the hub is the single machine label that appears in both entries. This is an O(1) shortcut worth knowing, but degree-counting is safer when you also want to validate the input.