Solving Leetcode Interviews in Seconds with AI: Sum of Distances in Tree
Introduction
In this blog post, we will explore how to solve the LeetCode problem "834" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are given the integer n and the array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. Return an array answer of length n where answer[i] is the sum of the distances between the ith node in the tree and all other nodes. Example 1: Input: n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]] Output: [8,12,6,10,10,10] Explanation: The tree is shown above. We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5) equals 1 + 1 + 2 + 2 + 2 = 8. Hence, answer[0] = 8, and so on. Example 2: Input: n = 1, edges = [] Output: [0] Example 3: Input: n = 2, edges = [[1,0]] Output: [1,1] Constraints: 1 <= n <= 3 * 104 edges.length == n - 1 edges[i].length == 2 0 <= ai, bi < n ai != bi The given input represents a valid tree.
Explanation
Here's an efficient solution to calculate the sum of distances between each node and all other nodes in the tree:
Root and Calculate Initial Sum: Choose an arbitrary node (e.g., node 0) as the root. Perform a Depth-First Search (DFS) to calculate the sum of distances from the root to all other nodes. Also, during this DFS, calculate the size of each subtree (number of nodes in the subtree).
Re-root and Update Sums: Perform another DFS. During this DFS, for each node, update the sum of distances based on the sum calculated for its parent. This is done using the formula:
answer[node] = answer[parent] - subtree_size[node] + (n - subtree_size[node]).Complexity: O(N) time and O(N) space, where N is the number of nodes in the tree.
Code
def sum_of_distances_in_tree(n: int, edges: list[list[int]]) -> list[int]:
"""
Calculates the sum of distances between each node and all other nodes in the tree.
Args:
n: The number of nodes in the tree.
edges: A list of edges, where each edge is a list of two integers representing the nodes connected by the edge.
Returns:
A list of integers, where the ith element is the sum of distances between the ith node and all other nodes.
"""
graph = [[] for _ in range(n)]
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
subtree_size = [0] * n
answer = [0] * n
def dfs1(node: int, parent: int) -> None:
"""
Calculates the size of each subtree and the initial sum of distances from the root.
"""
subtree_size[node] = 1
for neighbor in graph[node]:
if neighbor != parent:
dfs1(neighbor, node)
subtree_size[node] += subtree_size[neighbor]
answer[0] += answer[neighbor] + subtree_size[neighbor] # Accumulate distance to children
def dfs2(node: int, parent: int) -> None:
"""
Updates the sum of distances for each node based on the sum calculated for its parent.
"""
for neighbor in graph[node]:
if neighbor != parent:
answer[neighbor] = answer[node] - subtree_size[neighbor] + (n - subtree_size[neighbor])
dfs2(neighbor, node)
dfs1(0, -1) # Root at node 0
dfs2(0, -1)
return answer