Algorithm · Google · Hard
Requirements Given an undirected tree containing N vertices and N - 1 connections. Use the function signature sumOfDistancesInTree(N, edges), where N is the number of vertices and edges is a list of N - 1 undirected edge pairs [u, v]. Return an array ans such that ans[u] equals the total of the shortest-path lengths from node u to all remaining nodes. Start by describing the straightforward approach: run BFS or DFS from each vertex, which takes O(n²), before presenting the…
Checking your access…