Node With Highest Edge Score

medium graph hash map counting

Problem

You are given a directed graph with n nodes labeled 0 to n−1, where each node i has exactly one outgoing edge to node edges[i]. The edge score of a node is the sum of the labels of all nodes pointing to it. Return the node with the highest edge score; on a tie, return the smallest such index.

Inputedges = [1,0,0,0,0,7,7,5]
Output7
Nodes 5 and 6 point to node 7, so node 7 scores 5 + 6 = 11, the highest total.
Inputedges = [2,0,0,2]
Output0
Nodes 0 and 2 both score 3; node 0 wins the tie with the smaller index.

def edge_score(edges):
    n = len(edges)
    score = [0] * n
    for i in range(n):
        score[edges[i]] += i
    best = 0
    for i in range(1, n):
        if score[i] > score[best]:
            best = i
    return best
function edgeScore(edges) {
  const n = edges.length;
  const score = new Array(n).fill(0);
  for (let i = 0; i < n; i++) {
    score[edges[i]] += i;
  }
  let best = 0;
  for (let i = 1; i < n; i++) {
    if (score[i] > score[best]) best = i;
  }
  return best;
}
int edgeScore(int[] edges) {
    int n = edges.length;
    long[] score = new long[n];
    for (int i = 0; i < n; i++) {
        score[edges[i]] += i;
    }
    int best = 0;
    for (int i = 1; i < n; i++) {
        if (score[i] > score[best]) best = i;
    }
    return best;
}
int edgeScore(vector<int>& edges) {
    int n = edges.size();
    vector<long long> score(n, 0);
    for (int i = 0; i < n; i++) {
        score[edges[i]] += i;
    }
    int best = 0;
    for (int i = 1; i < n; i++) {
        if (score[i] > score[best]) best = i;
    }
    return best;
}
Time: O(n) Space: O(n)