Make Lexicographically Smallest Array by Swapping Elements (LeetCode 2948): Solution and Explanation
You may swap two values whenever they differ by at most limit. Return the smallest array in dictionary order that any sequence of such swaps can produce. The trick is that swappable values form groups that are contiguous runs once the values are sorted.
Intuition
Think of each value as a node, with an edge between two values whose difference is at most limit. Swaps along edges compose, so every connected component can be permuted in any order across the indices it occupies, and values never leave their component.
You do not need to build that graph. After sorting, if two neighbouring values differ by more than limit, no value on the left can reach any value on the right, because every value on the right is even further away. If neighbours differ by at most limit, they are directly connected. So the components are exactly the runs of the sorted order between gaps larger than limit.
Inside one component you are free to choose the order, and the lexicographically smallest choice is to put the smallest value at the leftmost index the component owns, the next smallest at the next index, and so on.
Groups never compete for indices, so doing this independently for every group gives the global optimum.
Approach: Sort, split at gaps, refill slots
- Build
order, the indices ofnumssorted by value. - Walk
orderwith a pointerk. Close the current group atkwhenk == nornums[order[k]] - nums[order[k - 1]] > limit. - For a closed group
order[start:k], sort its indices to get the slots it owns. - Write the group's values, which are already ascending, into those slots from left to right.
- Set
start = kand continue. Returnans.
Step-by-step example
nums = [1,5,3,9,8], limit = 2
- Sorted values with their indices: 1 (i0), 3 (i2), 5 (i1), 8 (i4), 9 (i3).
- 3 - 1 = 2 and 5 - 3 = 2 are both within limit, so 1, 3, 5 chain into one group.
- 8 - 5 = 3 > 2, so the first group closes. It owns indices 0, 1, 2 and gets values 1, 3, 5 in that order.
- 9 - 8 = 1 links 8 and 9. At the end the second group closes, owning indices 3, 4, and gets 8, 9.
- The answer is [1,3,5,8,9].
Code: Python, Java, C++
1class Solution:
2 def lexicographicallySmallestArray(self, nums: List[int], limit: int) -> List[int]:
3 n = len(nums)
4 order = sorted(range(n), key=lambda i: nums[i])
5 ans = [0] * n
6 start = 0
7 for k in range(1, n + 1):
8 if k == n or nums[order[k]] - nums[order[k - 1]] > limit:
9 group = order[start:k]
10 slots = sorted(group)
11 for idx, pos in enumerate(slots):
12 ans[pos] = nums[group[idx]]
13 start = k
14 return ans1class Solution {
2 public int[] lexicographicallySmallestArray(int[] nums, int limit) {
3 int n = nums.length;
4 Integer[] order = new Integer[n];
5 for (int i = 0; i < n; i++) order[i] = i;
6 Arrays.sort(order, (a, b) -> Integer.compare(nums[a], nums[b]));
7 int[] ans = new int[n];
8 int start = 0;
9 for (int k = 1; k <= n; k++) {
10 if (k == n || nums[order[k]] - nums[order[k - 1]] > limit) {
11 int[] slots = new int[k - start];
12 for (int j = start; j < k; j++) slots[j - start] = order[j];
13 Arrays.sort(slots);
14 for (int j = 0; j < slots.length; j++) {
15 ans[slots[j]] = nums[order[start + j]];
16 }
17 start = k;
18 }
19 }
20 return ans;
21 }
22}1class Solution {
2public:
3 vector<int> lexicographicallySmallestArray(vector<int>& nums, int limit) {
4 int n = nums.size();
5 vector<int> order(n);
6 iota(order.begin(), order.end(), 0);
7 sort(order.begin(), order.end(), [&](int a, int b) { return nums[a] < nums[b]; });
8 vector<int> ans(n);
9 int start = 0;
10 for (int k = 1; k <= n; k++) {
11 if (k == n || nums[order[k]] - nums[order[k - 1]] > limit) {
12 vector<int> slots(order.begin() + start, order.begin() + k);
13 sort(slots.begin(), slots.end());
14 for (int j = 0; j < (int)slots.size(); j++) {
15 ans[slots[j]] = nums[order[start + j]];
16 }
17 start = k;
18 }
19 }
20 return ans;
21 }
22};Time and space complexity
O(n log n)
Sorting the indices costs O(n log n). Sorting each group's indices costs at most O(n log n) in total because the groups partition the array.
O(n)
The sorted index order, the answer array and one group's slots.
Other approaches
Union-Find over sorted neighbours (time O(n log n), space O(n))
Sort indices by value, union each index with its sorted neighbour when the gap is at most limit, then collect each component's indices and values and sort both. It reaches the same groups with more machinery.
Repeated adjacent swaps (time O(n^2), space O(1))
Keep swapping any out-of-order pair that is allowed until nothing changes, like bubble sort with a constraint. It is correct but takes O(n^2) or worse and times out at 10^5 elements.
Common mistakes
- Only swapping values that are adjacent in the original array. Any two indices may swap, so position does not matter, only value distance.
- Assuming a group is limited to values within
limitof its smallest member. Chains can span far more thanlimit, for example 1, 3, 5 with limit 2. - Writing the group's values back in the order they were found instead of placing the smallest value in the leftmost slot.
- Using a comparator like
a - bon values near 10^9 in languages with 32-bit ints is fine here because values are positive, but subtracting negative values could overflow.
Frequently asked questions
Why are the groups contiguous in sorted order?
If sorted neighbours a and b differ by more than limit, every value below a is even further from every value above b, so no edge crosses that gap. Runs without such a gap are chained together directly.
Why is sorting each group into its own slots optimal?
A group's set of indices and set of values are fixed. Lexicographic order rewards the smallest possible value at the earliest index, and a group can place any of its values at any of its indices, so ascending values over ascending indices is best. Different groups do not share indices, so they do not interfere.
Is this a graph problem?
Yes. The groups are connected components of the graph where values within limit are joined. Sorting lets you find those components without building any edges.
What happens with duplicate values?
Equal values differ by 0, which is within any limit, so they always land in the same group. Their relative order does not matter because they are equal.