Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the adjacency list for the tree.
DSA Rust
let mut graph: Vec<Vec<usize>> = vec![Vec::new(); [1]];Attempts:
3 left
💡 Hint
Common Mistakes
Using the number of edges instead of nodes for graph size.
Initializing with zero length vector.
✗ Incorrect
We need to create an adjacency list with 'n' empty vectors, one for each node.
2fill in blank
mediumComplete the code to add an undirected edge between nodes u and v.
DSA Rust
graph[u].push([1]);
graph[v].push(u);Attempts:
3 left
💡 Hint
Common Mistakes
Pushing the same node twice.
Confusing u and v in push.
✗ Incorrect
To add an edge from u to v, push v into graph[u].
3fill in blank
hardFix the error in the DFS function signature to accept the parent node.
DSA Rust
fn dfs(node: usize, parent: usize, graph: &Vec<Vec<usize>>, dp: &mut Vec<usize>, diameter: &mut usize) [1]Attempts:
3 left
💡 Hint
Common Mistakes
Using void return type when a value is needed.
Returning boolean instead of length.
✗ Incorrect
The DFS returns the longest path length from the current node, so it must return usize.
4fill in blank
hardFill both blanks to update the diameter inside DFS.
DSA Rust
if first_max + second_max > *[1] { *[2] = first_max + second_max; }
Attempts:
3 left
💡 Hint
Common Mistakes
Updating dp[node] instead of diameter.
Using incorrect variables for comparison.
✗ Incorrect
We update the global diameter variable if the sum of two longest paths is greater.
5fill in blank
hardFill all three blanks to return the longest path from the current node.
DSA Rust
let longest_path = first_max + 1; dp[node] = longest_path; return [1];
Attempts:
3 left
💡 Hint
Common Mistakes
Returning first_max without adding 1.
Returning second_max or dp[node] incorrectly.
✗ Incorrect
We return the longest path length from the current node, which is longest_path.
