Description
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.
Β
Example 1:
Input: nums = [37,100]
Output: 1
Explanation:
- Compute the digit sum for each integer: [3 + 7 = 10, 1 + 0 + 0 = 1] β [10, 1]
- Sort the integers based on digit sum: [100, 37]. Swap37with100to obtain the sorted order.
- Thus, the minimum number of swaps required to rearrange numsis 1.
Example 2:
Input: nums = [22,14,33,7]
Output: 0
Explanation:
- Compute the digit sum for each integer: [2 + 2 = 4, 1 + 4 = 5, 3 + 3 = 6, 7 = 7] β [4, 5, 6, 7]
- Sort the integers based on digit sum: [22, 14, 33, 7]. The array is already sorted.
- Thus, the minimum number of swaps required to rearrange numsis 0.
Example 3:
Input: nums = [18,43,34,16]
Output: 2
Explanation:
- Compute the digit sum for each integer: [1 + 8 = 9, 4 + 3 = 7, 3 + 4 = 7, 1 + 6 = 7] β [9, 7, 7, 7]
- Sort the integers based on digit sum: [16, 34, 43, 18]. Swap18with16, and swap43with34to obtain the sorted order.
- Thus, the minimum number of swaps required to rearrange numsis 2.
Β
Constraints:
- 1 <= nums.length <= 105
- 1 <= nums[i] <= 109
- numsconsists of distinct positive integers.
Solution
Python3
class Solution:
    def minSwaps(self, nums: List[int]) -> int:
        N = len(nums)
        
        def getDigits(x):
            curr = 0
 
            while x > 0:
                curr += x % 10
                x //= 10
 
            return curr
 
        A = sorted(range(N), key = lambda i : (getDigits(nums[i]), nums[i]))
        res = 0
 
        for i in range(N):
            while A[i] != i:
                temp = A[A[i]]
                A[A[i]] = A[i]
                A[i] = temp
                
                res += 1
        
        return res