The node that appears in both edges[0] and edges[1] is the centre.
Approach 1
class Solution {
public int findCenter(int[][] edges) {
int a = edges[0][0], b = edges[0][1];
return a == edges[1][0] || a == edges[1][1] ? a : b;
}
}
Verdict: Uses the guarantee fully.
2
Degree count
Time O(n) Space O(n)
Count degrees; the node with degree n − 1 is the centre. Works for checking any graph.
Approach 2
class Solution {
public int findCenter(int[][] edges) {
int n = edges.length + 1;
int[] deg = new int[n + 1];
for (int[] e : edges) { deg[e[0]]++; deg[e[1]]++; }
for (int v = 1; v <= n; v++) if (deg[v] == n - 1) return v;
return -1;
}
}
Verdict: General but unnecessary here.
Before you submit
Edge cases and common mistakes
Test these inputs
Three nodes
Centre listed second in edges
Mistakes people make
Building an adjacency list when two edges suffice.