Approach
Sorting and greedy selection
For Minimum Swaps to Sort by Digit Sum, 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
- 41 lines of C++ from the credited upstream file 3551.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 4 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 int minSwaps(vector<int>& nums) {4 int ans = 0;5 unordered_set<int> seen;6 unordered_map<int, int> numToIndex;7 vector<int> sortedNums = nums;8 9 ranges::sort(sortedNums, ranges::less{}, [this](int num) {10 return pair<int, int>{getDigitSum(num), num};11 });12 13 for (int i = 0; i < sortedNums.size(); ++i)14 numToIndex[sortedNums[i]] = i;15 16 for (int i = 0; i < nums.size(); ++i) {17 if (seen.contains(i) || numToIndex[nums[i]] == i)18 continue;19 int cycleSize = 0;20 int j = i;21 while (seen.insert(j).second) {22 j = numToIndex[nums[j]];23 ++cycleSize;24 }25 ans += max(cycleSize - 1, 0);26 }27 28 return ans;29 }30 31 private:32 int getDigitSum(int num) {33 int sum = 0;34 while (num > 0) {35 sum += num % 10;36 num /= 10;37 }38 return sum;39 }40};41