Skip to content

3551. Minimum Swaps to Sort by Digit Sum 👍

  • Time: $O(\texttt{sort})$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Solution {
 public:
  int minSwaps(vector<int>& nums) {
    int ans = 0;
    unordered_set<int> seen;
    unordered_map<int, int> numToIndex;
    vector<int> sortedNums = nums;

    ranges::sort(sortedNums, ranges::less{}, [this](int num) {
      return pair<int, int>{getDigitSum(num), num};
    });

    for (int i = 0; i < sortedNums.size(); ++i)
      numToIndex[sortedNums[i]] = i;

    for (int i = 0; i < nums.size(); ++i) {
      if (seen.contains(i) || numToIndex[nums[i]] == i)
        continue;
      int cycleSize = 0;
      int j = i;
      while (seen.insert(j).second) {
        j = numToIndex[nums[j]];
        ++cycleSize;
      }
      ans += max(cycleSize - 1, 0);
    }

    return ans;
  }

 private:
  int getDigitSum(int num) {
    int sum = 0;
    while (num > 0) {
      sum += num % 10;
      num /= 10;
    }
    return sum;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution {
  public int minSwaps(int[] nums) {
    int ans = 0;
    Set<Integer> seen = new HashSet<>();
    Map<Integer, Integer> numToIndex = new HashMap<>();
    int[] sortedNums = Arrays.stream(nums)
                           .boxed()
                           .sorted(Comparator.comparingInt((Integer num) -> getDigitSum(num))
                                       .thenComparingInt(num -> num))
                           .mapToInt(Integer::intValue)
                           .toArray();

    for (int i = 0; i < sortedNums.length; ++i)
      numToIndex.put(sortedNums[i], i);

    for (int i = 0; i < nums.length; ++i) {
      if (seen.contains(i) || numToIndex.get(nums[i]) == i)
        continue;
      int cycleSize = 0;
      int j = i;
      while (seen.add(j)) {
        j = numToIndex.get(nums[j]);
        ++cycleSize;
      }
      ans += Math.max(cycleSize - 1, 0);
    }

    return ans;
  }

  private int getDigitSum(int num) {
    int sum = 0;
    while (num > 0) {
      sum += num % 10;
      num /= 10;
    }
    return sum;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
  def minSwaps(self, nums: list[int]) -> int:
    ans = 0
    seen = set()
    sortedNums = sorted(nums, key=lambda x: (self._getDigitSum(x), x))
    numToIndex = {num: i for i, num in enumerate(sortedNums)}

    for i, num in enumerate(nums):
      if i in seen or numToIndex[num] == i:
        continue
      cycleSize = 0
      j = i
      while j not in seen:
        seen.add(j)
        j = numToIndex[nums[j]]
        cycleSize += 1
      ans += max(cycleSize - 1, 0)
    return ans

  def _getDigitSum(self, num: int) -> int:
    return sum(int(digit) for digit in str(num))