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
Minimum Swaps to Sort by Digit Sum INPUT Original Array: nums 13 12 31 21 i=0 i=1 i=2 i=3 Digit Sum Calculation 13: 1+3 = 4 12: 1+2 = 3 31: 3+1 = 4 21: 2+1 = 3 Sort by digit sum, then by value Target Order: [12, 21, 13, 31] (sums: 3, 3, 4, 4) ALGORITHM STEPS 1 Calculate Digit Sums Compute sum for each element 2 Create Target Order Sort by sum, then value 3 Map Positions Find where each goes 4 Count Swaps Execute minimum swaps Swap Process: Swap 1: [13,12,31,21] --> [12,13,31,21] (swap 0,1) Swap 2: [12,13,31,21] --> [12,21,31,13] (swap 1,3) Then swap 2,3 for final FINAL RESULT Sorted Array: 12 21 13 31 sum=3 sum=3 sum=4 sum=4 OUTPUT 2 OK - Minimum Swaps Verification: - 12 (sum=3) comes first - 21 (sum=3, 21 > 12) - 13 (sum=4) next - 31 (sum=4, 31 > 13) Key Insight: Direct Position Mapping tracks where each element needs to go. By swapping elements into their correct positions and counting swaps, we find the minimum. Each swap places at least one element correctly, ensuring O(n) swaps in the worst case for cycle decomposition approach. TutorialsPoint - Minimum Swaps to Sort by Digit Sum | Direct Position Mapping Approach
Asked in
Google 25 Amazon 18 Microsoft 15
12.5K Views
Medium Frequency
~15 min Avg. Time
380 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen