Approach
Sorting and greedy selection
For Make Lexicographically Smallest Array by Swapping Elements, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 29 lines of Python from the credited upstream file 2948.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def lexicographicallySmallestArray(3 self,4 nums: list[int],5 limit: int,6 ) -> list[int]:7 ans = [0] * len(nums)8 numAndIndexes = sorted([(num, i) for i, num in enumerate(nums)])9 10 11 numAndIndexesGroups: list[list[tuple[int, int]]] = []12 13 for numAndIndex in numAndIndexes:14 if (not numAndIndexesGroups or15 numAndIndex[0] - numAndIndexesGroups[-1][-1][0] > limit):16 17 numAndIndexesGroups.append([numAndIndex])18 else:19 20 numAndIndexesGroups[-1].append(numAndIndex)21 22 for numAndIndexesGroup in numAndIndexesGroups:23 sortedNums = [num for num, _ in numAndIndexesGroup]24 sortedIndices = sorted([index for _, index in numAndIndexesGroup])25 for num, index in zip(sortedNums, sortedIndices):26 ans[index] = num27 28 return ans29