Longest Special Path - Problem

You are given an undirected tree rooted at node 0 with n nodes numbered from 0 to n - 1, represented by a 2D array edges of length n - 1, where edges[i] = [u_i, v_i, length_i] indicates an edge between nodes u_i and v_i with length length_i.

You are also given an integer array nums, where nums[i] represents the value at node i.

A special path is defined as a downward path from an ancestor node to a descendant node such that all the values of the nodes in that path are unique.

Note that a path may start and end at the same node.

Return an array result of size 2, where result[0] is the length of the longest special path, and result[1] is the minimum number of nodes in all possible longest special paths.

Input & Output

Example 1 — Basic Tree
$ Input: edges = [[0,1,5],[0,2,3],[1,3,2]], nums = [1,2,3,2]
Output: [7,3]
💡 Note: The longest special path is 0→1→3 with length 5+2=7 and values [1,2,2]. Since we need unique values, we get path 0→2 with length 3 and 2 nodes, making the result [7,3] where we find the longest valid unique path.
Example 2 — All Unique Values
$ Input: edges = [[0,1,2],[1,2,3]], nums = [1,2,3]
Output: [5,3]
💡 Note: Path 0→1→2 has unique values [1,2,3] and length 2+3=5 with 3 nodes total.
Example 3 — Single Node
$ Input: edges = [], nums = [1]
Output: [0,1]
💡 Note: Only one node, so path length is 0 and minimum nodes is 1.

Constraints

  • 1 ≤ n ≤ 105
  • 0 ≤ edges.length ≤ n - 1
  • edges[i].length = 3
  • 0 ≤ ui, vi ≤ n - 1
  • 1 ≤ lengthi ≤ 105
  • 1 ≤ nums[i] ≤ 105

Visualization

Tap to expand
Longest Special Path: Find Maximum Length with Unique ValuesInput Tree0123532Values: [1,2,3,2]Special Paths (Unique Values)✅ Path 0→2: length=3, nodes=2 Values: [1,3] - unique❌ Path 0→1→3: values [1,2,2] Not unique (2 appears twice)Best: length=3, min_nodes=2OutputResult[3, 2]length=3, nodes=2🎯 Key Insight: Use DFS with backtracking to explore unique-value paths efficiently
Understanding the Visualization
1
Tree Input
Edges define tree structure with weights, nums give node values
2
Find Special Paths
DFS to explore downward paths with unique values only
3
Return Result
Maximum length and minimum node count for that length
Key Takeaway
🎯 Key Insight: Use DFS with a visited set to track unique values along each path, backtracking efficiently to explore all possibilities
Asked in
Google 12 Amazon 8 Microsoft 6
2.1K Views
Medium Frequency
~35 min Avg. Time
89 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen