#2374
Node With Highest Edge Score
MediumHash TableGraph TheoryHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
In the optimal approach, we use a single pass to calculate the edge scores by leveraging the fact that each node has exactly one outgoing edge. This allows us to efficiently compute scores in O(n) time.
⚙️
Algorithm
3 steps- 1Step 1: Initialize an array `score` of size n with all zeros to store the edge scores for each node.
- 2Step 2: Iterate through the `edges` array. For each index `i`, add `i` to `score[edges[i]]` since `edges[i]` is the node that `i` points to.
- 3Step 3: After populating the scores, iterate through the `score` array to find the node with the maximum score, ensuring to return the smallest index in case of ties.
solution.py14 lines
1# Full working Python code
2
3def highestEdgeScore(edges):
4 n = len(edges)
5 score = [0] * n
6 for i in range(n):
7 score[edges[i]] += i
8 max_score = -1
9 result_node = -1
10 for i in range(n):
11 if score[i] > max_score or (score[i] == max_score and i < result_node):
12 max_score = score[i]
13 result_node = i
14 return result_nodeℹ
Complexity note: The time complexity is O(n) because we make a single pass through the edges to calculate scores and another pass to find the maximum. The space complexity is O(n) due to the score array used to store edge scores.
- 1Each node has exactly one outgoing edge, simplifying the score calculation.
- 2The edge score is cumulative based on the indices of nodes pointing to it.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.