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: 2
💡 Note: Digit sums: 13→4, 12→3, 31→4, 21→3. Target order: [12, 21, 13, 31]. Need 2 swaps: swap(0,2) and swap(1,3).
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 SumInput: [13, 12, 31, 21]13123121sum=4sum=3sum=4sum=3Target: [12, 21, 13, 31]12211331Position Mapping & CyclesCycle 1: 0→2→0Length 2, needs 1 swapCycle 2: 1→3→1Length 2, needs 1 swapTotal Swaps Needed: 2Sort by digit sum (ascending), then by value (ascending)
Understanding the Visualization
1
Input Analysis
Calculate digit sums for each number
2
Target Order
Sort by digit sum, then by value
3
Cycle Detection
Find cycles in position mapping
4
Count Swaps
Each cycle of length k needs k-1 swaps
Key Takeaway
🎯 Key Insight: Position cycles reveal the minimum swaps - each cycle of length k needs exactly k-1 swaps to resolve
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