File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 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+ };
You can’t perform that action at this time.
0 commit comments