Approach
Depth-first search
For Longest Special Path II, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 48 lines of Python from the credited upstream file 3486.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 3 def longestSpecialPath(4 self,5 edges: list[list[int]],6 nums: list[int]7 ) -> list[int]:8 maxLength = 09 minNodes = 110 graph = [[] for _ in range(len(nums))]11 12 for u, v, w in edges:13 graph[u].append((v, w))14 graph[v].append((u, w))15 16 prefix = [0]17 lastSeenDepth = {}18 19 def dfs(20 u: int,21 prev: int,22 leftBoundary: list[int],23 ) -> None:24 nonlocal maxLength, minNodes25 prevDepth = lastSeenDepth.get(nums[u], 0)26 lastSeenDepth[nums[u]] = len(prefix)27 28 if prevDepth != 0:29 leftBoundary = sorted(leftBoundary + [prevDepth])[-2:]30 31 length = prefix[-1] - prefix[leftBoundary[0]]32 nodes = len(prefix) - leftBoundary[0]33 if length > maxLength or (length == maxLength and nodes < minNodes):34 maxLength = length35 minNodes = nodes36 37 for v, w in graph[u]:38 if v == prev:39 continue40 prefix.append(prefix[-1] + w)41 dfs(v, u, leftBoundary)42 prefix.pop()43 44 lastSeenDepth[nums[u]] = prevDepth45 46 dfs(0, -1, leftBoundary=[0, 0])47 return [maxLength, minNodes]48