Skip to content

Commit 37e1217

Browse files
authored
Create 2948. Make Lexicographically Smallest Array by Swapping Elements (#696)
2 parents 3660c78 + c2d5ce1 commit 37e1217

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class Solution {
2+
public:
3+
vector<int> lexicographicallySmallestArray(vector<int>& nums, int limit) {
4+
// The Whole intuition was based on the fact that , if the elements are
5+
// within range of limit they will after a finite number of operation
6+
// sort themselves relatively . So we just sort them and create
7+
// different groups And finally using the groups identifier we just
8+
// update the final array >>>>
9+
vector<int> arr = nums; // O(N)
10+
sort(arr.begin(), arr.end()); // O(NLogN)
11+
int gno = 0;
12+
unordered_map<int, queue<int>> group; // O(N)
13+
map<int, int> connect;
14+
connect[arr[0]] = gno;
15+
group[gno].push(arr[0]);
16+
for (int i = 1; i < nums.size(); i++) { // O(N)
17+
if (abs(arr[i] - arr[i - 1]) <= limit) {
18+
group[gno].push(arr[i]);
19+
connect[arr[i]] = gno;
20+
} else {
21+
gno++;
22+
group[gno].push(arr[i]);
23+
connect[arr[i]] = gno;
24+
}
25+
}
26+
for (int i = 0; i < nums.size(); i++) { // O(N)
27+
int ele = nums[i];
28+
nums[i] = group[connect[nums[i]]].front();
29+
group[connect[nums[i]]].pop();
30+
}
31+
return nums;
32+
// Overall Time COmplexity :O(nlogn+n+n)
33+
// Overall Space Complexity :O(N)
34+
35+
// For idetification of groups we can use a higher level data structure
36+
// instead map >>>>
37+
// For Example DSU can be used to check whether certain is part of the
38+
// group or not
39+
}
40+
};

0 commit comments

Comments
 (0)