Approach
Depth-first search
For Longest Special Path, 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
- 51 lines of Java from the credited upstream file 3425.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 3 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 public int[] longestSpecialPath(int[][] edges, int[] nums) {3 List<Pair<Integer, Integer>>[] graph = new List[nums.length];4 5 for (int i = 0; i < nums.length; ++i)6 graph[i] = new ArrayList<>();7 8 for (int[] edge : edges) {9 final int u = edge[0];10 final int v = edge[1];11 final int w = edge[2];12 graph[u].add(new Pair<>(v, w));13 graph[v].add(new Pair<>(u, w));14 }15 16 int[] ans = new int[2];17 ans[0] = 0; 18 ans[1] = 1; 19 dfs(graph, 0, -1, 0, new ArrayList<>(List.of(0)),20 new HashMap<>(), nums, ans);21 return ans;22 }23 24 private void dfs(List<Pair<Integer, Integer>>[] graph, int u, int prev, int leftBoundary,25 List<Integer> prefix, Map<Integer, Integer> lastSeenDepth, int[] nums,26 int[] ans) {27 final int prevDepth = lastSeenDepth.getOrDefault(nums[u], 0);28 lastSeenDepth.put(nums[u], prefix.size());29 leftBoundary = Math.max(leftBoundary, prevDepth);30 31 final int length = prefix.get(prefix.size() - 1) - prefix.get(leftBoundary);32 final int nodes = prefix.size() - leftBoundary;33 if (length > ans[0] || (length == ans[0] && nodes < ans[1])) {34 ans[0] = length;35 ans[1] = nodes;36 }37 38 for (Pair<Integer, Integer> pair : graph[u]) {39 final int v = pair.getKey();40 final int w = pair.getValue();41 if (v == prev)42 continue;43 prefix.add(prefix.get(prefix.size() - 1) + w);44 dfs(graph, v, u, leftBoundary, prefix, lastSeenDepth, nums, ans);45 prefix.remove(prefix.size() - 1);46 }47 48 lastSeenDepth.put(nums[u], prevDepth);49 }50}51