Node With Highest Edge Score - Problem

You are given a directed graph with n nodes labeled from 0 to n - 1, where each node has exactly one outgoing edge.

The graph is represented by a given 0-indexed integer array edges of length n, where edges[i] indicates that there is a directed edge from node i to node edges[i].

The edge score of a node i is defined as the sum of the labels of all the nodes that have an edge pointing to i.

Return the node with the highest edge score. If multiple nodes have the same edge score, return the node with the smallest index.

Input & Output

Example 1 — Basic Graph
$ Input: edges = [1,0,0,2]
Output: 0
💡 Note: Node 0 has incoming edges from nodes 1 and 2, so score = 1 + 2 = 3. Node 1 has incoming edge from node 0, score = 0. Node 2 has incoming edge from node 3, score = 3. Node 0 has the highest score.
Example 2 — Tie Breaker
$ Input: edges = [1,2,3,0]
Output: 0
💡 Note: Each node has exactly one incoming edge: scores are [3,0,1,2]. Node 0 has the highest score of 3.
Example 3 — Self Loop
$ Input: edges = [0,1,1]
Output: 1
💡 Note: Node 0 points to itself (score = 0), nodes 1 and 2 point to node 1 (score = 1 + 2 = 3). Node 1 has the highest score.

Constraints

  • 2 ≤ edges.length ≤ 105
  • 0 ≤ edges[i] < edges.length

Visualization

Tap to expand
Node With Highest Edge Score INPUT Directed Graph (n=4 nodes) 0 1 2 3 edges array: 1 0 0 2 i=0 i=1 i=2 i=3 ALGORITHM STEPS 1 Initialize score array score[n] = [0,0,0,0] 2 Single pass: add scores score[edges[i]] += i i=0: edges[0]=1, score[1]+=0 i=1: edges[1]=0, score[0]+=1 i=2: edges[2]=0, score[0]+=2 i=3: edges[3]=2, score[2]+=3 score = [3, 0, 3, 0] 3 Find max score node Tie at 3: nodes 0 and 2 4 Return smallest index min(0, 2) = 0 FINAL RESULT Edge Scores for Each Node: Node 0: Score: 3 Node 1: Score: 0 Node 2: Score: 3 Node 3: Score: 0 OUTPUT 0 Node 0 has highest score (smallest index in tie) Key Insight: Single pass O(n) solution: For each node i, add i to score[edges[i]]. This accumulates all incoming edge labels for each target node. Track max score while iterating, preferring smaller index on ties. TutorialsPoint - Node With Highest Edge Score | Single Pass with Array
Asked in
Google 15 Amazon 12 Meta 8
23.5K Views
Medium Frequency
~15 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen