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
- 44 lines of C++ from the credited upstream file 2948.cpp.
- The implementation visibly relies on sequence storage.
- 5 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 public:3 vector<int> lexicographicallySmallestArray(vector<int>& nums, int limit) {4 vector<int> ans(nums.size());5 6 7 vector<vector<pair<int, int>>> numAndIndexesGroups;8 9 for (const pair<int, int>& numAndIndex : getNumAndIndexes(nums))10 if (numAndIndexesGroups.empty() ||11 numAndIndex.first - numAndIndexesGroups.back().back().first > limit) {12 13 numAndIndexesGroups.push_back({numAndIndex});14 } else {15 16 numAndIndexesGroups.back().push_back(numAndIndex);17 }18 19 for (const vector<pair<int, int>>& numAndIndexesGroup :20 numAndIndexesGroups) {21 vector<int> sortedNums;22 vector<int> sortedIndices;23 for (const auto& [num, index] : numAndIndexesGroup) {24 sortedNums.push_back(num);25 sortedIndices.push_back(index);26 }27 ranges::sort(sortedIndices);28 for (int i = 0; i < sortedNums.size(); ++i)29 ans[sortedIndices[i]] = sortedNums[i];30 }31 32 return ans;33 }34 35 private:36 vector<pair<int, int>> getNumAndIndexes(const vector<int>& nums) {37 vector<pair<int, int>> numAndIndexes;38 for (int i = 0; i < nums.size(); ++i)39 numAndIndexes.emplace_back(nums[i], i);40 ranges::sort(numAndIndexes);41 return numAndIndexes;42 }43};44