Skip to content

Commit e6d0667

Browse files
committed
Jan 25
1 parent 6192279 commit e6d0667

File tree

2 files changed

+40
-2
lines changed

2 files changed

+40
-2
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
from collections import deque
2+
from typing import List
3+
4+
5+
class Solution:
6+
def lexicographicallySmallestArray(self, nums: List[int], limit: int) -> List[int]:
7+
sorted_nums = sorted(nums)
8+
9+
# group elements based on the limit
10+
groups = [deque([sorted_nums[0]])]
11+
group_map = {sorted_nums[0]: 0}
12+
for num in sorted_nums[1:]:
13+
if abs(num - groups[-1][-1]) <= limit:
14+
groups[-1].append(num)
15+
else:
16+
groups.append(deque([num]))
17+
group_map[num] = len(groups) - 1
18+
19+
# replace element with the smallest element in its group
20+
return [groups[group_map[num]].popleft() for num in nums]
21+
22+
23+
def main():
24+
nums = [1, 5, 3, 9, 8]
25+
limit = 2
26+
assert Solution().lexicographicallySmallestArray(nums, limit) == [1, 3, 5, 8, 9]
27+
28+
nums = [1, 7, 6, 18, 2, 1]
29+
limit = 3
30+
assert Solution().lexicographicallySmallestArray(nums, limit) == [1, 6, 7, 18, 1, 2]
31+
32+
nums = [1, 7, 28, 19, 10]
33+
limit = 3
34+
assert Solution().lexicographicallySmallestArray(nums, limit) == [1, 7, 28, 19, 10]
35+
36+
37+
if __name__ == '__main__':
38+
main()

2025-01-January-LeetCoding-Challenge/README.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
| January 22 | [1765. Map of Highest Peak](https://leetcode.com/problems/map-of-highest-peak/) | Medium | Solved |
2828
| January 23 | [1267. Count Servers that Communicate](https://leetcode.com/problems/count-servers-that-communicate/) | Medium | Solved |
2929
| January 24 | [802. Find Eventual Safe States](https://leetcode.com/problems/find-eventual-safe-states/) | Medium | Unsolved |
30-
| January 25 | []() | | |
30+
| January 25 | [2948. Make Lexicographically Smallest Array by Swapping Elements](https://leetcode.com/problems/make-lexicographically-smallest-array-by-swapping-elements/) | Medium | Solved |
3131
| January 26 | []() | | |
3232
| January 27 | []() | | |
3333
| January 28 | []() | | |
@@ -40,5 +40,5 @@
4040
| Level | Problems | Solved | Unsolved |
4141
| --- | --- | --- | --- |
4242
| Easy | 4 | 4 | 0 |
43-
| Medium | 17 | 14 | 3 |
43+
| Medium | 18 | 15 | 3 |
4444
| Hard | 2 | 0 | 2 |

0 commit comments

Comments
 (0)