#3486

Longest Special Path II

Hard
ArrayHash TableTreeDepth-First SearchPrefix SumHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses Depth-First Search (DFS) while maintaining a dynamic record of the path values and their counts. This allows us to efficiently check the special condition without needing to revisit nodes.

⚙️

Algorithm

4 steps
  1. 1Step 1: Build the graph from the edges.
  2. 2Step 2: Perform a DFS from the root node, maintaining a count of values in the current path.
  3. 3Step 3: Check if the path is special by ensuring at most one value appears twice.
  4. 4Step 4: Update the maximum path length and the minimum number of distinct nodes if the current path is valid.
solution.py33 lines
1# Full working Python code
2from collections import defaultdict
3
4
5def longest_special_path(edges, nums):
6    graph = defaultdict(list)
7    for u, v, length in edges:
8        graph[u].append((v, length))
9        graph[v].append((u, length))
10
11    max_length = 0
12    min_nodes = float('inf')
13
14    def dfs(node, parent, path_values, path_length):
15        nonlocal max_length, min_nodes
16        path_values[nums[node]] += 1
17        is_special = sum(1 for count in path_values.values() if count > 1) <= 1
18
19        if is_special:
20            if path_length > max_length:
21                max_length = path_length
22                min_nodes = len(path_values)
23            elif path_length == max_length:
24                min_nodes = min(min_nodes, len(path_values))
25
26        for neighbor, length in graph[node]:
27            if neighbor != parent:
28                dfs(neighbor, node, path_values, path_length + length)
29
30        path_values[nums[node]] -= 1
31
32    dfs(0, -1, defaultdict(int), 0)
33    return [max_length, min_nodes]

Complexity note: The time complexity is O(n) because we visit each node once, and the space complexity is O(n) due to the storage of path values.

  • 1Understanding tree traversal is crucial for solving problems involving paths.
  • 2Maintaining state during DFS can help efficiently check conditions without redundant calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.