3219. Make Lexicographically Smallest Array by Swapping Elements
My accepted Python solution to LeetCode problem 3219, Make Lexicographically Smallest Array by Swapping Elements, running in 334ms.
- Difficulty: Medium
- Python
- Runtime 334ms
- Memory 43.1MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 334ms, memory 43.1MB, accepted 2026-01-01.
class Solution:
def lexicographicallySmallestArray(self, nums: List[int], limit: int) -> List[int]:
n = len(nums)
# Create list of (value, original_index)
indexed = [(num, i) for i, num in enumerate(nums)]
indexed.sort()
result = [0] * n
# Group elements that can be swapped with each other
i = 0
while i < n:
# Find the group of elements where consecutive elements differ by <= limit
group = [indexed[i]]
j = i + 1
while j < n and indexed[j][0] - indexed[j-1][0] <= limit:
group.append(indexed[j])
j += 1
# Get the sorted values and sorted positions for this group
values = sorted([g[0] for g in group])
positions = sorted([g[1] for g in group])
# Assign smallest values to smallest positions
for k in range(len(group)):
result[positions[k]] = values[k]
i = j
return result