#3551

Minimum Swaps to Sort by Digit Sum

Medium
ArrayHash TableSortingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal 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
  1. 1Step 1: Calculate the digit sums and create a list of tuples (digit sum, original index).
  2. 2Step 2: Sort this list based on digit sums and values to get the target positions.
  3. 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.