Longest Special Path II Problem
Description
LeetCode Problem 3486.
You are given an undirected tree rooted at node 0, with n nodes numbered from 0 to n - 1. This is 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 in which all node values are distinct, except for at most one value that may appear twice.
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.
Example 1:
Input: edges = [[0,1,1],[1,2,3],[1,3,1],[2,4,6],[4,7,2],[3,5,2],[3,6,5],[6,8,3]], nums = [1,1,0,3,1,2,1,1,0]
Output: [9,3]
Explanation:
In the image below, nodes are colored by their corresponding values in nums.

The longest special paths are 1 -> 2 -> 4 and 1 -> 3 -> 6 -> 8, both having a length of 9. The minimum number of nodes across all longest special paths is 3.
Example 2:
Input: edges = [[1,0,3],[0,2,4],[0,3,5]], nums = [1,1,0,2]
Output: [5,2]
Explanation:

The longest path is 0 -> 3 consisting of 2 nodes with a length of 5.
Constraints:
2 <= n <= 5 * 10^4edges.length == n - 1edges[i].length == 30 <= u_i, v_i < n1 <= length_i <= 10^3nums.length == n0 <= nums[i] <= 5 * 10^4- The input is generated such that
edgesrepresents a valid tree.
Solution
Approach: DFS with a Sliding Window on the Root Path
Every special path is a vertical segment of the path from the root to some node, so we run a DFS and keep a window [left, d] over the current root path (d is the depth of the current node) that is the longest valid window ending at the current node. Keep also dist[d], the distance from the root to the node at depth d, so a window's length is dist[d] - dist[left].
Two extra values describe the window:
last[v]: the depth of the deepest ancestor holding valuev(or -1).dup: the depth of the first copy of the one repeated value inside the window (or -1 if the window has no repeat).
When we step down to a node with value v and p = last[v]:
- If
p < left, the value is new to the window and nothing changes. - Otherwise
vbecomes a second copy. If the window already holds a repeat (dup >= left), one of the two repeats must go, soleftjumps tomin(dup, p) + 1. Thendup = max(dup, p).
Update the best answer with the window's length and node count (d - left + 1), preferring fewer nodes on equal length. When the DFS leaves a node, restore last[v]. The DFS uses an explicit stack, since a tree can be 50,000 levels deep.
Complexity: O(n) time and O(n) space.
class Solution:
def longestSpecialPath(self, edges: List[List[int]], nums: List[int]) -> List[int]:
n = len(nums)
g = [[] for _ in range(n)]
for u, v, w in edges:
g[u].append((v, w))
g[v].append((u, w))
last = [-1] * (max(nums) + 1) # depth of the latest ancestor holding each value
dist = [0] * n # dist[d]: distance from the root to the node at depth d of the current path
left = [0] * n # start depth of the window ending at each node
dup = [-1] * n # depth of the first copy of the repeated value in that window (-1: none)
prev = [-1] * n
dep = [0] * n
par = [-1] * n
ptr = [0] * n
best, cnt = 0, 1
prev[0] = last[nums[0]]
last[nums[0]] = 0
stack = [0]
while stack:
u = stack[-1]
if ptr[u] < len(g[u]):
v, w = g[u][ptr[u]]
ptr[u] += 1
if v == par[u]:
continue
par[v] = u
d = dep[u] + 1
dep[v] = d
dist[d] = dist[d - 1] + w
l, f = left[u], dup[u]
p = last[nums[v]]
if p >= l:
if f >= l:
l = min(f, p) + 1
f = max(f, p)
prev[v] = p
last[nums[v]] = d
left[v], dup[v] = l, f
length = dist[d] - dist[l]
if length > best or (length == best and d - l + 1 < cnt):
best, cnt = length, d - l + 1
stack.append(v)
else:
last[nums[u]] = prev[u]
stack.pop()
return [best, cnt]