← Meta Interview Insights

Meta·Software Engineer·Technical Phone Screen·Intermediate

Intermediate
Jun 2026

Summary

Meta SWE coding round with a tree problem that looks straightforward until you actually sit down with it. Nothing too exotic but the weighted edges add a layer that trips you up if you're not careful.

Questions Asked (1)

Q1

Given a weighted tree, find the length of the longest path between any two nodes.

Algorithms & Data Structures
Author's notes

My first instinct was BFS and that was a mistake.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Clarify that the tree is weighted and the path length is the sum of edge weights. Then explain that the longest path (diameter) can be found using two DFS/BFS passes: first from any node to find the farthest node A, then from A to find the farthest node B; the distance between A and B is the diameter. Alternatively, use tree DP to compute the maximum downward path and combine the two longest downward paths at each node.

Pro tip: Mention that the two-pass method works because the farthest node from any node is an endpoint of a diameter, and that tree DP is more general for other problems. Also, discuss handling negative weights: if edges can be negative, the two-pass method fails, and you need tree DP with careful initialization.

1. Clarify the problem

Confirm that the tree is weighted, edges are undirected, and path length is the sum of edge weights. Ask if edge weights can be negative.

2. Choose an approach

Select either the two-pass DFS/BFS method (for non-negative weights) or tree DP (for general weights). Explain the reasoning behind your choice.

3. Detail the algorithm

For two-pass: pick any node, run DFS to find farthest node A, then from A run DFS to find farthest node B; return distance A-B. For tree DP: for each node, compute the longest downward path and the sum of the two longest downward paths from its children; track the maximum.

4. Analyze complexity

State that both approaches run in O(n) time and O(n) space, where n is the number of nodes.

5. Discuss edge cases

Mention handling of a single node (diameter 0), negative weights (if applicable), and large trees (recursion depth).

Key Points to Mention

  • Definition of tree diameter and its relation to the longest path.
  • Two-pass DFS/BFS method: proof that the farthest node from any node is an endpoint of a diameter.
  • Tree DP approach: computing the longest downward path and combining the top two at each node.
  • Time and space complexity: O(n) for both methods.
  • Handling negative edge weights: two-pass method fails, tree DP works with proper initialization.
  • Implementation details: iterative DFS to avoid recursion limit, or increasing recursion limit.

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.