3551. Minimum Swaps to Sort by Digit Sum Medium
1/**
2 * [3551] Minimum Swaps to Sort by Digit Sum
3 *
4 * 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.
5 * Return the minimum number of swaps required to rearrange nums into this sorted order.
6 * A swap is defined as exchanging the values at two distinct positions in the array.
7 *
8 * <strong class="example">Example 1:
9 * <div class="example-block">
10 * Input: <span class="example-io">nums = [37,100]</span>
11 * Output: <span class="example-io">1</span>
12 * Explanation:
13 *
14 * Compute the digit sum for each integer: [3 + 7 = 10, 1 + 0 + 0 = 1] → [10, 1]
15 * Sort the integers based on digit sum: [100, 37]. Swap 37 with 100 to obtain the sorted order.
16 * Thus, the minimum number of swaps required to rearrange nums is 1.
17 * </div>
18 * <strong class="example">Example 2:
19 * <div class="example-block">
20 * Input: <span class="example-io">nums = [22,14,33,7]</span>
21 * Output: <span class="example-io">0</span>
22 * Explanation:
23 *
24 * Compute the digit sum for each integer: [2 + 2 = 4, 1 + 4 = 5, 3 + 3 = 6, 7 = 7] → [4, 5, 6, 7]
25 * Sort the integers based on digit sum: [22, 14, 33, 7]. The array is already sorted.
26 * Thus, the minimum number of swaps required to rearrange nums is 0.
27 * </div>
28 * <strong class="example">Example 3:
29 * <div class="example-block">
30 * Input: <span class="example-io">nums = [18,43,34,16]</span>
31 * Output: <span class="example-io">2</span>
32 * Explanation:
33 *
34 * Compute the digit sum for each integer: [1 + 8 = 9, 4 + 3 = 7, 3 + 4 = 7, 1 + 6 = 7] → [9, 7, 7, 7]
35 * Sort the integers based on digit sum: [16, 34, 43, 18]. Swap 18 with 16, and swap 43 with 34 to obtain the sorted order.
36 * Thus, the minimum number of swaps required to rearrange nums is 2.
37 * </div>
38 *
39 * Constraints:
40 *
41 * 1 <= nums.length <= 10^5
42 * 1 <= nums[i] <= 10^9
43 * nums consists of distinct positive integers.
44 *
45 */
46pub struct Solution {}
47
48// problem: https://leetcode.com/problems/minimum-swaps-to-sort-by-digit-sum/
49// discuss: https://leetcode.com/problems/minimum-swaps-to-sort-by-digit-sum/discuss/?currentPage=1&orderBy=most_votes&query=
50
51// submission codes start here
52
53impl Solution {
54 pub fn min_swaps(nums: Vec<i32>) -> i32 {
55 0
56 }
57}
58
59// submission codes end
60
61#[cfg(test)]
62mod tests {
63 use super::*;
64
65 #[test]
66 fn test_3551() {
67 }
68}
69Back
© 2026 bowen.ge All Rights Reserved.