Longest Special Path II - Problem

You're exploring a tree structure where each node has a unique value. Your mission is to find the longest special path - a downward journey from any ancestor to its descendant with an interesting twist!

Given an undirected tree rooted at node 0 with n nodes (numbered 0 to n-1), represented by edges and node values, you need to find special paths where:

  • All node values are distinct, OR
  • At most one value appears exactly twice

Input:

  • edges: 2D array where edges[i] = [u_i, v_i, length_i] represents an edge between nodes u_i and v_i with given length
  • nums: Array where nums[i] is the value at node i

Output: Return [maxLength, minNodes] where:

  • maxLength: Length of the longest special path
  • minNodes: Minimum number of nodes among all longest special paths

Input & Output

example_1.py — Basic Tree
$ Input: edges = [[0,1,5], [1,2,3]], nums = [1,2,1]
Output: [8, 3]
💡 Note: The longest special path is 0→1→2 with values [1,2,1]. Since value 1 appears twice (allowed), this path has length 5+3=8 and uses 3 nodes.
example_2.py — Complex Tree
$ Input: edges = [[0,1,2], [0,2,3], [1,3,4]], nums = [1,1,2,3]
Output: [6, 3]
💡 Note: The longest special path is 0→1→3 with values [1,1,3]. The first duplicate is allowed, giving length 2+4=6 with 3 nodes. Path 0→2 has length 3 but only 2 nodes.
example_3.py — Single Node
$ Input: edges = [], nums = [5]
Output: [0, 1]
💡 Note: With only one node, the longest path has length 0 (no edges) and uses 1 node.

Constraints

  • 1 ≤ n ≤ 105
  • edges.length == n - 1
  • edges[i] = [ui, vi, lengthi]
  • 0 ≤ ui, vi < n
  • 1 ≤ lengthi ≤ 109
  • 1 ≤ nums[i] ≤ 105
  • The graph forms a valid tree

Visualization

Tap to expand
Longest Special Path II INPUT Tree Structure (rooted at 0) 0 val=1 w=5 1 val=2 w=3 2 val=1 edges = [[0,1,5],[1,2,3]] nums = [1, 2, 1] ALGORITHM (DFS) 1 Start DFS from root Track path values & lengths 2 Check duplicate values Allow at most 1 duplicate 3 Update path window Sliding window technique 4 Track max length Min nodes for max length Path: 0 --> 1 --> 2 0 5 1 3 2 Values: [1, 2, 1] Value 1 appears twice - OK! Total length = 5 + 3 = 8 FINAL RESULT Longest Special Path Found 0 5 1 3 2 3 nodes, length = 8 OUTPUT [8, 3] maxLength = 8 minNodes = 3 OK - Valid special path (one duplicate allowed) Key Insight: A "special path" allows all distinct values OR exactly one value appearing twice. Use DFS with a sliding window to track valid ancestor-to-descendant paths. When a value appears more than twice, shrink the window from the start. Track both maximum length and minimum node count. TutorialsPoint - Longest Special Path II | DFS Approach
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
32.4K Views
Medium-High Frequency
~25 min Avg. Time
1.2K 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