# How can I select the function and its derivative with the smallest or largest index from a list of function and function derivatives?

I have a list of functions and their derivatives.

How can I select the function and its derivative with the smallest or largest index, provided that both the function and its derivative are in the list?

For example, given the list

vars = {U[1][t], U[2][t], U[3][t], U[5][t], U[6][t], U[7][t], U[3]'[t], U[5]'[t], U[6]'[t]},

I want to select the function and its derivative with the smallest index, which would be {U[3][t], U[3]'[t]}.

Use Cases to retrieve the indices of functions and derivatives, then Intersection to get only those that are present in both lists. Afterward, use Min or Max or MinMax to retrieve the smallest or the largest.

MinMax@Intersection[Cases[vars, U[x_][t] :> x], Cases[vars, U[x_]'[t] :> x]]
(* {3, 6} *)

vars = {U[1][t], U[2][t], U[3][t], U[5][t], U[6][t], U[7][t],
U[3]'[t], U[5]'[t], U[6]'[t]}

min = First@Intersection[D[vars, t], vars]

{Integrate[min, t], min}


{U[3][t], Derivative[1][U[3]][t]}

MinMax @ Cases[{a_, __} :> a] @ Split @ Sort @
Cases[vars, U[a_][_] | _[_][U[a_]][_] :> a]


{3, 6}