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: [8,3]
💡 Note: The longest special path is 2→0→1 with unique values [3,1,2] and total length 3+5=8 using 3 nodes. This gives the result [8,3].
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 INPUT Tree Structure (rooted at 0) 0 [1] 5 3 1 [2] 2 [3] 2 3 [2] edges: [[0,1,5],[0,2,3],[1,3,2]] nums: [1,2,3,2] ALGORITHM STEPS 1 DFS from Root Track path values and lengths 2 Check Uniqueness Use hashmap for node values 3 Sliding Window Maintain valid path start 4 Backtrack Restore state when returning Exploring Path 0-->1-->3: 0 val=1 --> 1 val=2 --> 3 val=2! Duplicate value 2 detected Adjust window start to node 1 Length: 5+2=7, Nodes: 3 (path 0-->1-->3 with unique 1,2) FINAL RESULT Longest Special Path Found: 0 5 1 2 2 3 Output: [7, 3] Length = 7 (5+2) Min nodes = 3 (0,1,3) Key Insight: Use DFS with backtracking to explore all downward paths from ancestors to descendants. Maintain a sliding window with a hashmap to track the last occurrence of each node value. When a duplicate value is found, adjust the window start to maintain path uniqueness. Track both maximum length and minimum node count for paths achieving that length. TutorialsPoint - Longest Special Path | Optimized DFS with Backtracking
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