Taro Logo

Node With Highest Edge Score

Medium
Asked by:
Juspay
3 views
Topics:
ArraysGraphs

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.

Example 1:

Input: edges = [1,0,0,0,0,7,7,5]
Output: 7
Explanation:
- The nodes 1, 2, 3 and 4 have an edge pointing to node 0. The edge score of node 0 is 1 + 2 + 3 + 4 = 10.
- The node 0 has an edge pointing to node 1. The edge score of node 1 is 0.
- The node 7 has an edge pointing to node 5. The edge score of node 5 is 7.
- The nodes 5 and 6 have an edge pointing to node 7. The edge score of node 7 is 5 + 6 = 11.
Node 7 has the highest edge score so return 7.

Example 2:

Input: edges = [2,0,0,2]
Output: 0
Explanation:
- The nodes 1 and 2 have an edge pointing to node 0. The edge score of node 0 is 1 + 2 = 3.
- The nodes 0 and 3 have an edge pointing to node 2. The edge score of node 2 is 0 + 3 = 3.
Nodes 0 and 2 both have an edge score of 3. Since node 0 has a smaller index, we return 0.

Constraints:

  • n == edges.length
  • 2 <= n <= 105
  • 0 <= edges[i] < n
  • edges[i] != i

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the range of node identifiers in the graph, and are they guaranteed to be contiguous integers starting from 0 up to $N - 1$?
  2. Can a node have a self-loop (i.e., an edge pointing from a node to itself), and if so, how should that affect its edge score?
  3. Is the graph guaranteed to have at least one incoming edge for every node, or could some nodes have an edge score of zero?
  4. If multiple nodes achieve the exact same highest edge score, the prompt states to return the smaller numerical identifier—does this tie-breaking rule apply universally across all nodes?
  5. Are multiple directed edges allowed between the same pair of nodes in the input list, and should duplicate edges be counted multiple times toward the target node's edge score?

Brute Force Solution

Approach

Imagine you are tracking a game where players pass a ball to each other and you need to figure out who received the most total points from incoming passes. The brute force approach involves looking at every single person one by one, gathering all the points they received, and comparing everyone's totals.

Here's how the algorithm would work step-by-step:

  1. Pick the first person on your list to evaluate.
  2. Look at every single pass made in the game to find all the ones directed to this person.
  3. Add up the values of all those incoming passes to get a total score for this person.
  4. Write down this person's total score.
  5. Move on to the next person on the list and repeat the exact same process of gathering and adding up their incoming passes.
  6. Continue doing this until you have calculated a total score for every single person.
  7. Compare all the final scores you wrote down and select the person with the highest total.
  8. If there is a tie for the highest score, pick the person who appears first on the list.

Code Implementation

def highest_edge_score(outgoing_edges):
    total_nodes_count = len(outgoing_edges)
    highest_score_found = -1
    best_node_identifier = -1

    # Evaluate each node individually to calculate its total incoming score from scratch
    for current_target_node in range(total_nodes_count):
        accumulated_edge_score = 0
        
        # Scan the entire edge list to find every incoming pass directed to this node
        for source_node_index in range(total_nodes_count):
            if outgoing_edges[source_node_index] == current_target_node:
                accumulated_edge_score += source_node_index

        # Update our best candidate if this node strictly beats the previous maximum score
        if accumulated_edge_score > highest_score_found:
            highest_score_found = accumulated_edge_score
            best_node_identifier = current_target_node

    return best_node_identifier

Big(O) Analysis

Time Complexity
O(n²) – For each of the n nodes in the graph, we iterate through the entire edges array of size n to find and sum all incoming passes directed to that specific node. This requires iterating through n nodes and performing n checks for each, resulting in approximately n times n operations. Dropping the constant factors, this simplifies to a quadratic time complexity of O(n²).
Space Complexity
O(n) – To keep track of the total scores for every person as described in the steps, we need an auxiliary array or hash map of size N, where N is the total number of players. This data structure stores the accumulated incoming pass values for each individual node. As the number of players N increases, the memory required to store these intermediate scores grows proportionally. Therefore, the auxiliary space complexity simplifies to Big O of N.

Optimal Solution

Approach

To find the node with the highest edge score efficiently, we can calculate and track the total incoming points for every single node in a single pass. By keeping a running total of the points each node receives from others, we can easily identify the winner without having to constantly recheck the connections.

Here's how the algorithm would work step-by-step:

  1. Create a scoreboard to keep track of the total incoming points accumulated by each node.
  2. Look at every connection between the starting points and ending points one by one.
  3. For each connection, take the points assigned by the starting point and add them directly to the running total of the ending point on the scoreboard.
  4. As you update the scoreboard, keep a mental note of which node currently holds the highest total score.
  5. If you encounter a tie where a new node matches the highest score, favor the node that has the smaller identifier number.
  6. Once all connections have been reviewed, the node remaining with the highest total score is your final answer.

Code Implementation

def edge_score(edges):
    total_nodes = len(edges)
    
    score_board = [0] * total_nodes

    # Accumulate incoming edge scores for each node in a single pass
    for source_node, target_node in enumerate(edges):
        score_board[target_node] += source_node

    highest_score = -1
    best_node_identifier = -1

    # Track the maximum score while favoring the smaller node index on ties
    for node_identifier, current_score in enumerate(score_board):
        if current_score > highest_score:
            highest_score = current_score
            best_node_identifier = node_identifier

    # Return the node with the highest accumulated score
    return best_node_identifier

Big(O) Analysis

Time Complexity
O(n) – Let n be the number of nodes, which is also the length of the edges array representing the connections. We iterate through the edges array exactly once to calculate the incoming points for each destination node. During this single pass, we perform constant time additions and update our maximum score tracker. This linear traversal of the input scales directly with the number of connections, resulting in O(n) total operations.
Space Complexity
O(n) – To implement the scoreboard for tracking incoming points described in step 1, we utilize an auxiliary array or hash map of size N, where N represents the total number of nodes. As the input edges are processed, this data structure stores the accumulated score for each node independently of the input itself. The variables used to track the current highest score and winning node identifier only require a constant amount of extra memory. Therefore, the total auxiliary space complexity scales linearly with the number of nodes N, simplifying to Big O of N.

Edge Cases

Minimum valid input size where the edges array has only one element
How to Handle:
The loop processes the single edge, adding the source node to the target node's score and immediately returning that target node.
Multiple nodes achieving the exact same maximum edge score
How to Handle:
We iterate through the accumulated scores from smallest node identifier to largest, ensuring we select the smaller identifier upon a tie.
A single node receives all incoming edges from every other node
How to Handle:
The score accumulation array correctly sums all incoming node labels for that single target without index out of bounds issues.
Graph contains self-loops where a node points to itself
How to Handle:
The algorithm adds the node's own label to its edge score just like any other incoming edge.
Maximum possible node identifiers and edge counts up to the problem constraints
How to Handle:
We use a 64-bit integer array or hash map for score storage to prevent potential integer overflow from large summations.
Nodes with zero incoming edges receiving no score updates
How to Handle:
These nodes remain at a score of zero and naturally lose out during the maximum score search unless all scores are zero.
Disconnected or isolated nodes that never appear as edge targets
How to Handle:
Since scores default to zero, these nodes are simply ignored when finding the maximum edge score.
Graph contains cycles among multiple nodes
How to Handle:
Since we only sum incoming edges and do not traverse paths recursively, cycles do not cause infinite loops or stack overflows.