Node With Highest Edge Score — Medium Problem & Solution
A directed graph has n nodes labelled 0 to n - 1, and every node has exactly one outgoing edge: node i points to node edges[i] (never to itself).
- Difficulty: Medium
- Topics: Hash Table, Graph
- Asked at: Amazon, Google
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
A directed graph has n nodes labelled 0 to n - 1, and every node has exactly one outgoing edge: node i points to node edges[i] (never to itself).
The edge score of a node v is the sum of the labels of all nodes that point to v.
Return the node with the highest edge score. If several nodes share the highest score, return the one with the smallest label.
Example 1
Input: edges = [1,4,1,4,2]
Output: 2
Explanation: Node 1 is pointed to by 0 and 2 (score 2), node 4 by 1 and 3 (score 4), node 2 by 4 (score 4). Nodes 2 and 4 tie; 2 is smaller.
Example 2
Input: edges = [2,0,0,2]
Output: 0
Explanation: Node 0 scores 1 + 2 = 3 and node 2 scores 0 + 3 = 3.
Constraints
n == edges.length2 <= n <= 10^50 <= edges[i] < nedges[i] != i
How to solve Node With Highest Edge Score
The edge score is a weighted in-degree: node i adds weight i to the node it points to. One accumulation pass and one arg-max pass solve it.
Approach
- Create a 64-bit
scorearray of lengthn, all zero. - For each
i, additoscore[edges[i]]. - Scan nodes from 0 to
n - 1, keeping the node whose score is strictly greater than the best so far. - Return that node.
Why it works
Every edge i -> edges[i] is counted exactly once, in the score of its target, so the array holds the exact edge scores. Updating only on a strictly greater score while scanning in increasing label order returns the smallest label among the maxima.
Complexity
- Time —
O(n) - Space —
O(n)
Pitfalls
- With
n = 10^5a node can score almost5 * 10^9, which overflows a 32-bit integer. - Use
>rather than>=so ties keep the smaller label. - Nodes nobody points to score 0 and can still be the answer only if every score is 0 (impossible here, but the scan handles it).
Reference solution
Python
from typing import List
def edgeScore(edges: List[int]) -> int:
n = len(edges)
score = [0] * n
for i, t in enumerate(edges):
score[t] += i
best = 0
for v in range(1, n):
if score[v] > score[best]:
best = v
return bestJavaScript
var edgeScore = function(edges) {
var n = edges.length;
var score = new Array(n).fill(0);
for (var i = 0; i < n; i++) score[edges[i]] += i;
var best = 0;
for (var v = 1; v < n; v++) if (score[v] > score[best]) best = v;
return best;
};Also on the editorial tab: C, C#, C++, Go, Java, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 302 hash table problems · the whole catalogue
Learn the technique: Hashing: Hash Maps and Hash Sets · Graph Data Structure