Skip to main content

Minimum Swaps to Sort by Digit Sum - Solution & Explanation

MediumArrayHash TableSorting7 min readAsked at: Google
Practice this problem

Problem Statement

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.

 

Example 1:

Input: nums = [37,100]

Output: 1

Explanation:

  • Compute the digit sum for each integer: [3 + 7 = 10, 1 + 0 + 0 = 1] → [10, 1]
  • Sort the integers based on digit sum: [100, 37]. Swap 37 with 100 to obtain the sorted order.
  • Thus, the minimum number of swaps required to rearrange nums is 1.

Example 2:

Input: nums = [22,14,33,7]

Output: 0

Explanation:

  • Compute the digit sum for each integer: [2 + 2 = 4, 1 + 4 = 5, 3 + 3 = 6, 7 = 7] → [4, 5, 6, 7]
  • Sort the integers based on digit sum: [22, 14, 33, 7]. The array is already sorted.
  • Thus, the minimum number of swaps required to rearrange nums is 0.

Example 3:

Input: nums = [18,43,34,16]

Output: 2

Explanation:

  • Compute the digit sum for each integer: [1 + 8 = 9, 4 + 3 = 7, 3 + 4 = 7, 1 + 6 = 7] → [9, 7, 7, 7]
  • Sort the integers based on digit sum: [16, 34, 43, 18]. Swap 18 with 16, and swap 43 with 34 to obtain the sorted order.
  • Thus, the minimum number of swaps required to rearrange nums is 2.

 

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 109
  • nums consists of distinct positive integers.

Approach Overview

Problem Overview: You are given an array of integers. The array must be reordered so numbers appear in ascending order of their digit sum. The task is to compute the minimum number of swaps required to transform the original array into that sorted order.

Approach 1: Brute Force Swap Simulation (O(n^2) time, O(1) space)

Compute the digit sum for every number, then build the target sorted array based on digit sums. Iterate through the array and whenever the current element is not the element that should appear at that position in the sorted order, find its correct location and swap. Each misplaced element may require scanning the rest of the array to locate its destination, which makes the approach quadratic. This method demonstrates the core idea behind swap counting but becomes slow for large inputs.

Approach 2: Sort + Cycle Detection (O(n log n) time, O(n) space)

Create pairs of (digitSum, value, originalIndex) and sort them by digit sum (and value if needed to maintain deterministic ordering). Once sorted, the problem reduces to computing the minimum swaps required to transform the original index arrangement into the sorted index arrangement. This is done by detecting permutation cycles: if a cycle contains k elements, it requires k - 1 swaps. Iterate through the array, mark visited indices, and count cycle sizes. Sorting contributes O(n log n) time while cycle traversal runs in O(n). This is the standard optimal technique used in many minimum swap problems.

Approach 3: Hash Map Index Tracking (O(n log n) time, O(n) space)

Another implementation keeps a mapping from value (or value plus digit sum) to its index using a hash table. After building the target sorted array using sorting, iterate through positions and swap elements into their correct place while updating the index map. Each swap fixes at least one element, so the number of swaps is minimized. The hash lookup allows constant-time index updates, but the dominant cost remains sorting.

Recommended for interviews: The Sort + Cycle Detection approach is what interviewers typically expect. It shows that you recognize the problem as a permutation cycle problem after sorting by digit sum. Starting with the brute-force swap idea demonstrates understanding, but identifying cycles and counting k - 1 swaps per cycle shows stronger algorithmic maturity. The implementation naturally combines array traversal with sorting and visited tracking.

Solution

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force Swap SimulationO(n^2)O(1)Good for understanding swap mechanics or very small arrays
Sort + Cycle DetectionO(n log n)O(n)Optimal general solution for minimum swap problems after sorting
Hash Map Index TrackingO(n log n)O(n)Useful when implementing direct swap placement with fast index lookup

Video Solution

3551. Minimum Swaps to Sort by Digit Sum | Weekly Contest 450 | Leetcode • Rapid Syntax • 1,927 views views

Watch 5 more video solutions →

Frequently Asked Questions

Is Minimum Swaps to Sort by Digit Sum easy or hard?
The problem is usually rated Medium because it requires recognizing that the task reduces to a permutation cycle problem after sorting by digit sum. Implementing the cycle detection correctly is the main challenge.
Minimum Swaps to Sort by Digit Sum Python/Java solution
Typical implementations compute the digit sum for each number, store tuples containing the digit sum and original index, sort them, and then detect permutation cycles to count swaps. The same logic works in Python, Java, C++, Go, and TypeScript with standard sorting and array traversal.
How to solve Minimum Swaps to Sort by Digit Sum in O(n)?
A strict O(n) solution is generally not feasible because the array must be ordered by digit sum, which requires sorting in the general case. The best practical approach is O(n log n): compute digit sums, sort elements by those sums, then count swaps using cycle detection.
What is the best approach for Minimum Swaps to Sort by Digit Sum?
The most efficient approach is sorting the array by digit sum and then counting swaps using permutation cycle detection. After sorting, each cycle of length k in the index permutation requires k-1 swaps. This method runs in O(n log n) time due to sorting and O(n) space for visited tracking.
Is Minimum Swaps to Sort by Digit Sum asked at Google/Amazon/Meta?
Variants of minimum swap and permutation cycle problems frequently appear in interviews at companies like Google, Amazon, and Meta. While this exact problem may vary, the underlying technique of sorting followed by cycle detection is a common interview pattern.
What data structure is used in Minimum Swaps to Sort by Digit Sum?
The solution primarily uses arrays along with sorting utilities. Many implementations also use a visited boolean array for cycle detection or a hash table to track element indices during swaps.
What is the time complexity of Minimum Swaps to Sort by Digit Sum?
The optimal solution runs in O(n log n) time because the array must first be sorted by digit sum. After sorting, cycle detection to compute the minimum swaps runs in O(n). The space complexity is O(n) for storing visited indices or auxiliary structures.

Ready to solve this problem?

Practice Minimum Swaps to Sort by Digit Sum with our built-in code editor and test cases.

Practice on FleetCode