|
| 1 | +2948\. Make Lexicographically Smallest Array by Swapping Elements |
| 2 | + |
| 3 | +Medium |
| 4 | + |
| 5 | +You are given a **0-indexed** array of **positive** integers `nums` and a **positive** integer `limit`. |
| 6 | + |
| 7 | +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`. |
| 8 | + |
| 9 | +Return _the **lexicographically smallest array** that can be obtained by performing the operation any number of times_. |
| 10 | + |
| 11 | +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`. |
| 12 | + |
| 13 | +**Example 1:** |
| 14 | + |
| 15 | +**Input:** nums = [1,5,3,9,8], limit = 2 |
| 16 | + |
| 17 | +**Output:** [1,3,5,8,9] |
| 18 | + |
| 19 | +**Explanation:** Apply the operation 2 times: |
| 20 | + |
| 21 | +- Swap nums[1] with nums[2]. The array becomes [1,3,5,9,8] |
| 22 | + |
| 23 | +- Swap nums[3] with nums[4]. The array becomes [1,3,5,8,9] |
| 24 | + |
| 25 | +We cannot obtain a lexicographically smaller array by applying any more operations. |
| 26 | + |
| 27 | +Note that it may be possible to get the same result by doing different operations. |
| 28 | + |
| 29 | +**Example 2:** |
| 30 | + |
| 31 | +**Input:** nums = [1,7,6,18,2,1], limit = 3 |
| 32 | + |
| 33 | +**Output:** [1,6,7,18,1,2] |
| 34 | + |
| 35 | +**Explanation:** Apply the operation 3 times: |
| 36 | + |
| 37 | +- Swap nums[1] with nums[2]. The array becomes [1,6,7,18,2,1] |
| 38 | + |
| 39 | +- Swap nums[0] with nums[4]. The array becomes [2,6,7,18,1,1] |
| 40 | + |
| 41 | +- Swap nums[0] with nums[5]. The array becomes [1,6,7,18,1,2] |
| 42 | + |
| 43 | +We cannot obtain a lexicographically smaller array by applying any more operations. |
| 44 | + |
| 45 | +**Example 3:** |
| 46 | + |
| 47 | +**Input:** nums = [1,7,28,19,10], limit = 3 |
| 48 | + |
| 49 | +**Output:** [1,7,28,19,10] |
| 50 | + |
| 51 | +**Explanation:** [1,7,28,19,10] is the lexicographically smallest array we can obtain because we cannot apply the operation on any two indices. |
| 52 | + |
| 53 | +**Constraints:** |
| 54 | + |
| 55 | +* <code>1 <= nums.length <= 10<sup>5</sup></code> |
| 56 | +* <code>1 <= nums[i] <= 10<sup>9</sup></code> |
| 57 | +* <code>1 <= limit <= 10<sup>9</sup></code> |
0 commit comments