Leetcode 2374: Node With Highest Edge Score

grid47
grid47
Exploring patterns and algorithms
Mar 14, 2024 6 min read

You are given a directed graph where each node has exactly one outgoing edge, and the graph is represented by an integer array edges of size n. The value at edges[i] indicates that there is a directed edge from node i to node edges[i]. The edge score of a node i is the sum of all the node labels that have an edge pointing to i. Your task is to find the node with the highest edge score. If multiple nodes have the same edge score, return the node with the smallest index.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer array `edges` of size n where each element in the array represents an outgoing edge from node i.
Example: edges = [1, 0, 0, 0, 0, 7, 7, 5]
Constraints:
• 2 <= n <= 10^5
• 0 <= edges[i] < n
• edges[i] != i
Output: Return the index of the node with the highest edge score. If multiple nodes have the same edge score, return the smallest index.
Example: Output: 7
Constraints:
Goal: The goal is to compute the edge score for each node and determine the node with the highest edge score.
Steps:
• 1. Initialize a map to store the sum of edge scores for each node.
• 2. Iterate through the `edges` array and update the edge scores for the target nodes.
• 3. Track the node with the highest edge score, resolving ties by selecting the smallest index.
Goal: The number of nodes in the graph will always be between 2 and 10^5, and each node has an outgoing edge to a distinct target.
Steps:
• The graph will always have at least 2 nodes.
• Each node points to a valid target node, and no node points to itself.
Assumptions:
• The graph is a directed graph where each node has exactly one outgoing edge.
Input: Input: edges = [1, 0, 0, 0, 0, 7, 7, 5]
Explanation: For this input, node 0 has the highest edge score, as the sum of labels of nodes pointing to it is 10 (nodes 1, 2, 3, 4). Node 7 has an edge score of 11 (nodes 5 and 6), which is the highest, so the output is 7.

Input: Input: edges = [2, 0, 0, 2]
Explanation: In this case, both nodes 0 and 2 have an edge score of 3. Since node 0 has the smallest index, the output is 0.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus