Assign node labels to maximize the total edge sum
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Microsoft. It tests graph, greedy and sorting.
You are given an undirected graph with n nodes numbered 0 to n - 1 and a list edges, where edges[i] = [a, b] is an edge between nodes a and b.
Give every node a label so that the labels are exactly the integers 1 to n, each used once. The value of an edge (u, v) is label(u) + label(v).
Implement max_edge_sum(n: int, edges: list[list[int]]) -> int that returns the largest possible total value over all edges, taken over every valid labeling.
Constraints
1 <= n <= 5 * 10^40 <= len(edges) <= 5 * 10^4-
0 <= a, b < n,a != b; no duplicate edges - Some nodes may have no edges.
Example 1
n = 4, edges = [[0,1],[0,2],[0,3]]
Output: 18
Node 0 touches all three edges, so it gets label 4; nodes 1, 2, 3 get labels 1, 2, 3. Total = (4+1) + (4+2) + (4+3) = 18.
Example 2
n = 5, edges = [[3,4]]
Output: 9
Only one edge exists, so its endpoints take the two largest labels, 4 and 5.
Clarifying questions
- Are self-loops or duplicate edges possible? (The rules say no.)
- Must every label
1..nbe used, even on isolated nodes? (Yes, but they add nothing.) - Can the total overflow 32 bits? (Up to about
5 * 10^9.) - Should we return the labeling too?
What a strong answer covers
- Rewrites the total as the sum of
label(v) x degree(v), because each node's label is counted once per edge it touches. - Gives the largest labels to the nodes with the highest degrees, and explains why (the rearrangement inequality, or a swap argument).
- Sorts the degrees, or counts them, since degrees are at most
n. That is O(n + m), or O(n log n + m). - Tests the star, a single edge, no edges, and a graph where every node has the same degree.
Follow-ups
- Return the labeling.
- The edge value is
label(u) x label(v): why the degree argument no longer works. - Edges have weights.
- The labels are an arbitrary multiset of values.
Where it's asked
What it tests
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
