Minimum Swaps to Sort by Digit Sum - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [13, 12, 31, 21]
›
Output:
3
💡 Note:
Digit sums: 13→4, 12→3, 31→4, 21→3. Target order: [12, 21, 13, 31]. This requires one cycle of length 4, needing 3 swaps to resolve.
Example 2 — Already Sorted
$
Input:
nums = [10, 11, 12]
›
Output:
0
💡 Note:
Digit sums: 10→1, 11→2, 12→3. Array is already sorted by digit sum, so 0 swaps needed.
Example 3 — Same Digit Sum
$
Input:
nums = [21, 12]
›
Output:
1
💡 Note:
Both have digit sum 3, but 12 < 21, so target order is [12, 21]. Need 1 swap.
Constraints
- 1 ≤ nums.length ≤ 50
- 1 ≤ nums[i] ≤ 50
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code