← Questions

Assign node labels to maximize the total edge sum

0
MicrosoftCoding

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^4
  • 0 <= 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..n be 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

graph · greedy · sorting

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding