Sum of Distances in Tree
Updated
Problem statement
You are given a connected undirected tree with n nodes numbered from 0 to n - 1. The array edges contains the tree's n - 1 edges.
Return an integer array answer of length n, where answer[u] is the sum of the shortest-path distances from node u to every other node.
Function
sumOfDistancesInTree(n: int, edges: int[][]) → int[]Examples
Example 1
n = 6edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]return = [8,12,6,10,10,10]From node 0, the distances are 0, 1, 1, 2, 2, 2, which sum to 8. Repeating the definition for each root gives the returned array.
Example 2
n = 1edges = []return = [0]The only node has distance 0 to itself.
Constraints
1 <= n <= 30000edges.length = n - 1- Every row of
edgesis[u, v]with0 <= u, v < nandu != v. edgesforms one connected tree.
More Google Onsite Interview questions
- Evaluate a Nested Math ExpressionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Distinct Subset SumsONSITE INTERVIEW · Seen Nov 2026
- Playlist With No Same Artist in a RowONSITE INTERVIEW · Seen Nov 2026
- Route Pattern MatcherPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Delete Nodes and Return Forest RootsONSITE INTERVIEW · Seen Nov 2026
- Dice-Walk Winning ProbabilityPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- First and Last Target Position in a Mountain ArrayONSITE INTERVIEW · Seen Nov 2026
- Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- 0/1 Knapsack with Weight and Volume LimitsONSITE INTERVIEW · Seen Nov 2026
- Batched Subsequence Word MatchesONSITE INTERVIEW · Seen Nov 2026
Similar questions at other companies
- Distance Sums to Special Nodes in a Weighted TreeNutanix · ONSITE INTERVIEWNutanix interview questions
- Minimum Leaf Path Sum over All RootsInfosys · OAInfosys interview questions
- Maximum Strength of Every NeuronMicrosoft · OAMicrosoft interview questions
- Tree Node With Maximum BeautyC3.ai · OAC3.ai interview questions
- Maximum Reservoir PowerWells Fargo · OAWells Fargo interview questions
- File Encryption Tree OptimizationDatabricks · PHONE SCREEN · ONSITE INTERVIEWDatabricks interview questions
- Binary Tree Maximum Path SumGoldman Sachs · ONSITE INTERVIEWGoldman Sachs interview questions
- Binary Tree Maximum Path SumBloomberg LP · ONSITE INTERVIEWBloomberg LP interview questions
- Binary Tree Maximum Path SumGlobalization Partners · ONSITE INTERVIEW
- Longest Decreasing Matrix Path with Limited RelaxationsDuolingo · ONSITE INTERVIEWDuolingo interview questions