[LeetCode] Minimum Swaps to Sort by Digit Sum

3551. Minimum Swaps to Sort by Digit Sum

You are given an array nums of distinct positive integers. You need to sort the array in increasing order based on the sum of the digits of each number. If two numbers have the same digit sum, the smaller number appears first in the sorted order.

Return the minimum number of swaps required to rearrange nums into this sorted order.

A swap is defined as exchanging the values at two distinct positions in the array.

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
41
42
43
44
import "sort"

func calc(n int) int {
res := 0
for n > 0 {
res += n % 10
n /= 10
}
return res
}

func minSwaps(nums []int) int {
n := len(nums)
sum := make([]int, n)
for i, v := range nums {
sum[i] = calc(v)
}
ord := make([]int, n)
now := make([]int, n)
gogo := make([]int, n)
for i := 0; i < n; i++ {
ord[i] = i
now[i] = i
}
sort.Slice(ord, func(i, j int) bool {
a, b := ord[i], ord[j]
if sum[a] == sum[b] {
return nums[a] < nums[b]
}
return sum[a] < sum[b]
})
for i := 0; i < n; i++ {
gogo[ord[i]] = i
}
res := 0
for i := 0; i < n; i++ {
for now[i] != ord[i] {
res++
j := gogo[now[i]]
now[i], now[j] = now[j], now[i]
}
}
return res
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/05/18/PS/LeetCode/minimum-swaps-to-sort-by-digit-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.