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,5,4,9]
💡 Note: Elements 5,3 can swap (diff=2). Elements 9,4 can swap (diff=5>2, but 3 can connect to both forming one group). Result: sort [5,3] to [3,5], and [9,4] to [4,9].

Constraints

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

Visualization

Tap to expand
Make Lexicographically Smallest Array by Swapping1539Input: [1,5,3,9], limit=2Find swappable pairs: |5-3|=2≤2 ✓1359Group [5,3] sorted → [3,5]Output: [1,3,5,9] - Lexicographically smallest
Understanding the Visualization
1
Input
Array with elements that can swap if difference ≤ limit
2
Group
Find connected components of swappable elements
3
Sort
Sort each group to get lexicographically smallest result
Key Takeaway
🎯 Key Insight: Elements that can be swapped transitively form connected components - sort each component for optimal result
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