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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code