Sponsored
Sponsored
Use these hints if you're stuck. Try solving on your own first.
Construct a virtual graph where all elements in <code>nums</code> are nodes and the pairs satisfying the condition have an edge between them.
Instead of constructing all edges, we only care about the connected components.
Can we use DSU?
Sort <code>nums</code>. Now we just need to consider if the consecutive elements have an edge to check if they belong to the same connected component. Hence, all connected components become a list of position-consecutive elements after sorting.
For each index of <code>nums</code> from <code>0</code> to <code>nums.length - 1</code> we can change it to the current minimum value we have in its connected component and remove that value from the connected component.