Make Lexicographically Smallest Array by Swapping Elements (LeetCode 2948): Solution and Explanation

Medium
Array
Union find
Sorting

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

  1. Build order, the indices of nums sorted by value.
  2. Walk order with a pointer k. Close the current group at k when k == n or nums[order[k]] - nums[order[k - 1]] > limit.
  3. For a closed group order[start:k], sort its indices to get the slots it owns.
  4. Write the group's values, which are already ascending, into those slots from left to right.
  5. Set start = k and continue. Return ans.

Step-by-step example

nums = [1,5,3,9,8], limit = 2
  1. Sorted values with their indices: 1 (i0), 3 (i2), 5 (i1), 8 (i4), 9 (i3).
  2. 3 - 1 = 2 and 5 - 3 = 2 are both within limit, so 1, 3, 5 chain into one group.
  3. 8 - 5 = 3 > 2, so the first group closes. It owns indices 0, 1, 2 and gets values 1, 3, 5 in that order.
  4. 9 - 8 = 1 links 8 and 9. At the end the second group closes, owning indices 3, 4, and gets 8, 9.
  5. 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 ans
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

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.

Space

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 limit of its smallest member. Chains can span far more than limit, 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 - b on 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.