#3551
Minimum Swaps to Sort by Digit Sum
MediumArrayHash TableSortingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
By sorting based on digit sums and using a cycle detection method, we can calculate swaps efficiently.
⚙️
Algorithm
3 steps- 1Step 1: Calculate the digit sums and create a list of tuples (digit sum, original index).
- 2Step 2: Sort this list based on digit sums and values to get the target positions.
- 3Step 3: Use cycle detection to count the number of swaps needed.
solution.py16 lines
1def minSwaps(nums):
2 def digit_sum(x): return sum(int(d) for d in str(x))
3 indexed_nums = [(digit_sum(num), i) for i, num in enumerate(nums)]
4 indexed_nums.sort()
5 visited = [False] * len(nums)
6 swaps = 0
7 for i in range(len(nums)):
8 if visited[i] or indexed_nums[i][1] == i:
9 continue
10 cycle_size = 0
11 while not visited[i]:
12 visited[i] = True
13 i = indexed_nums[i][1]
14 cycle_size += 1
15 swaps += cycle_size - 1
16 return swapsℹ
Complexity note: The sorting step dominates the complexity, making it O(n log n).
- 1Understanding digit sums is crucial for sorting.
- 2Cycle detection efficiently counts swaps.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.