Problem Description
Given a 0-indexed array of positive integers nums and a positive integer limit, you can swap any two numbers nums[i] and nums[j] if |nums[i] - nums[j]| <= limit. The goal is to perform any number of operations to obtain the lexicographically smallest array possible.
Key Insights
- The swap condition can be modeled as an edge connecting two indices if the absolute difference of their corresponding values is ≤ limit.
- Indices connected through a sequence of such valid swaps form a connected component, meaning elements within that component can be arbitrarily rearranged.
- To obtain the lexicographically smallest outcome, for each connected component, sort the indices (positions) and the corresponding values separately; then reassign the smallest available value to the smallest index.
- Instead of checking every pair (which is O(n²)), note that sorting the array by value and performing union on adjacent pairs (when the gap between consecutive values is ≤ limit) efficiently builds the connected components.
Space and Time Complexity
Time Complexity: O(n log n) – due to sorting the array and the per-component sorting. Space Complexity: O(n) – for union-find structure and auxiliary storage for grouping indices.
Solution
We solve the problem by using a union-find (disjoint-set) data structure. The key steps are:
- Pair each element with its index.
- Sort these pairs by the element value.
- Iterate through the sorted pairs and union adjacent indices when their value difference is ≤ limit. This efficiently groups indices that can swap indirectly.
- For each connected component, collect its indices, sort them, and also sort their corresponding numbers.
- Place the sorted numbers into the array at the sorted indices to ensure the lexicographically smallest arrangement.
- Return the resulting array.