Make Lexicographically Smallest Array by Swapping Elements - Problem

You are given a 0-indexed array of positive integers nums and a positive integer limit.

In one operation, you can choose any two indices i and j and swap nums[i] and nums[j] if |nums[i] - nums[j]| <= limit.

Return the lexicographically smallest array that can be obtained by performing the operation any number of times.

An array a is lexicographically smaller than an array b if in the first position where a and b differ, array a has an element that is less than the corresponding element in b. For example, the array [2,10,3] is lexicographically smaller than the array [10,2,3] because they differ at index 0 and 2 < 10.

Input & Output

Example 1 — Basic Swapping
$ Input: nums = [1,5,3,9], limit = 2
Output: [1,3,5,9]
💡 Note: We can swap 5 and 3 since |5-3|=2≤2. After swapping: [1,3,5,9] which is lexicographically smallest.
Example 2 — No Valid Swaps
$ Input: nums = [1,7,5,3], limit = 1
Output: [1,7,5,3]
💡 Note: No adjacent values have difference ≤1, so no swaps are possible. Return original array.
Example 3 — Multiple Connected Components
$ Input: nums = [1,5,3,9,4], limit = 2
Output: [1,3,4,9,5]
💡 Note: Elements can be grouped: 1↔3 (diff=2), 5↔3 (diff=2), 5↔4 (diff=1), 3↔4 (diff=1). This forms one connected component {1,3,4,5} at positions [0,1,2,4] and isolated element {9} at position [3]. Sorting the component gives [1,3,4,5], resulting in [1,3,4,9,5].

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109
  • 0 ≤ limit ≤ 109

Visualization

Tap to expand
Make Lexicographically Smallest Array INPUT nums array: 1 i=0 5 i=1 3 i=2 9 i=3 limit = 2 Swap allowed if: |nums[i] - nums[j]| <= 2 Valid Swaps: |5-3|=2 <= 2 OK |1-3|=2 <= 2 OK |9-5|=4 > 2 NO |9-1|=8 > 2 NO ALGORITHM STEPS 1 Sort with indices [(1,0), (3,2), (5,1), (9,3)] 2 Group by Union-Find Union if diff <= limit Group 1: {1, 3, 5} Group 2: {9} 3 Sort each group G1: [1,3,5] G2: [9] 4 Place back by index Assign smallest to earliest idx 0 --> 1 idx 1 --> 3 (was 5) idx 2 --> 5 (was 3) idx 3 --> 9 FINAL RESULT Output Array: 1 3 5 9 Output: [1,3,5,9] Lexicographically Smallest! Swap Performed: 5 <--> 3 at i=1,2 Before: [1, 5, 3, 9] After: [1, 3, 5, 9] Time: O(n log n) | Space: O(n) Key Insight: Elements that can be swapped (directly or transitively) form connected groups. Using Union-Find, we identify these groups efficiently. Within each group, elements can be rearranged freely. To get the lexicographically smallest result, we sort each group and assign the smallest values to the earliest indices within that group. TutorialsPoint - Make Lexicographically Smallest Array by Swapping Elements | Union-Find with Sorting
Asked in
Google 45 Meta 32 Amazon 28 Microsoft 25
28.5K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen