Skip to main content

Sum of Sortable Integers - Solution & Explanation

Practice this problem

Problem Statement

You are given an integer array nums of length n.

An integer k is called sortable if k divides n and you can sort nums in non-decreasing order by sequentially performing the following operations:

  • Partition nums into consecutive subarrays of length k.
  • Cyclically rotate each subarray independently any number of times to the left or to the right.

Return an integer denoting the sum of all possible sortable integers k.

 

Example 1:

Input: nums = [3,1,2]

Output: 3

Explanation:​​​​​​​

  • For n = 3, possible divisors are 1 and 3.
  • For k = 1: each subarray has one element. No rotation can sort the array.
  • For k = 3: the single subarray [3, 1, 2] can be rotated once to produce [1, 2, 3], which is sorted.
  • Only k = 3 is sortable. Hence, the answer is 3.

Example 2:

Input: nums = [7,6,5]

Output: 0

Explanation:

  • For n = 3, possible divisors are 1 and 3.
  • For k = 1: each subarray has one element. No rotation can sort the array.
  • For k = 3: the single subarray [7, 6, 5] cannot be rotated into non-decreasing order.
  • No k is sortable. Hence, the answer is 0.

Example 3:

Input: nums = [5,8]

Output: 3

Explanation:​​​​​​​

  • For n = 2, possible divisors are 1 and 2.
  • Since [5, 8] is already sorted, every divisor is sortable. Hence, the answer is 1 + 2 = 3.

 

Constraints:

  • 1 <= n == nums.length <= 105
  • 1 <= nums[i] <= 105

Approach Overview

Problem Overview: You are given a collection of integers and must identify which ones are sortable. An integer is considered sortable if its digits can be rearranged so the resulting number has digits in non‑decreasing order. The task is to compute the sum of all integers that satisfy this condition.

Approach 1: Brute Force Digit Permutations (O(n * d!))

The most direct idea is to generate every permutation of the digits of each number and check if any permutation forms a non‑decreasing sequence. Convert the number to a string, generate permutations, and validate whether digits increase or stay equal as you scan from left to right. The first valid permutation marks the integer as sortable. This approach quickly becomes impractical because the number of permutations grows factorially with the digit count (d!). Space complexity is O(d!) due to storing permutations during generation.

Approach 2: Greedy Digit Sorting (O(n * d log d))

A much simpler observation: if digits can be rearranged to become non‑decreasing, sorting the digits directly gives that arrangement. Convert the integer to a digit array, sort it, and verify the resulting sequence is valid under the problem constraints. Since sorting produces the lexicographically smallest ordering, the check becomes trivial. Each integer requires sorting d digits, giving O(d log d) time and O(d) extra space. This approach relies on basic sorting operations and works well for moderate digit counts.

Approach 3: Digit Frequency Counting (O(n * d))

You can avoid explicit sorting by counting how many times each digit (0–9) appears. A number can be reconstructed in non‑decreasing order by iterating through the digit frequency array from 0 to 9 and rebuilding the sequence. Because the digit range is fixed, counting runs in linear time relative to digit count. Each integer is processed in O(d) time with O(1) auxiliary space. This pattern appears often in problems involving frequency counting or greedy digit reconstruction.

Approach 4: Digit DP / Bitmask Validation (O(n * d * 10))

If additional constraints exist (for example, restrictions on leading zeros or positional rules), a digit dynamic programming approach can validate whether a sorted reconstruction is allowed. The digits are processed with state tracking for position and allowed digits. Although heavier than counting, this technique handles more complex rules while staying roughly linear in digit length. Space complexity typically remains O(d * 10) for the DP state.

Recommended for interviews: The digit frequency counting solution is usually the expected answer. Starting with the brute force permutation idea shows understanding of the definition, but recognizing that sorted order can be reconstructed directly using counts demonstrates stronger algorithmic thinking and reduces the complexity from factorial to linear per number.

Solutions for this problem are being prepared.

Try solving it yourself

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force Digit PermutationsO(n * d!)O(d!)Conceptual baseline or very small digit counts
Greedy Digit SortingO(n * d log d)O(d)Simple and reliable for typical constraints
Digit Frequency CountingO(n * d)O(1)Optimal solution when only digit order matters
Digit DP ValidationO(n * d * 10)O(d * 10)Useful when additional positional constraints exist

Video Solution

Leetcode 3886 | Sum of Sortable Integers | Leetcode weekly contest 495CodeWithMeGuys594 views views

Watch 5 more video solutions →

Frequently Asked Questions

Is Sum of Sortable Integers easy or hard?
The problem is typically categorized as Hard because recognizing the correct digit manipulation strategy is not obvious at first glance. Brute force permutation approaches are too slow, so the challenge is identifying the frequency-counting optimization that reduces the complexity to linear time per number.
Sum of Sortable Integers Python/Java solution
Most implementations convert each number into digits, compute digit frequencies, and verify the sortable condition. The logic is identical across languages: iterate digits, update a 10-element count array, and rebuild digits in ascending order before adding valid numbers to the sum.
How to solve Sum of Sortable Integers in O(n)?
Process each integer independently and count digit frequencies using a fixed array of size 10. Rebuild the digits in ascending order using the counts and validate the sortable property. Since digit counting is linear in the number of digits, the total complexity becomes O(n · d).
What is the best approach for Sum of Sortable Integers?
Digit frequency counting is typically the best approach. Count how many times each digit (0–9) appears, then reconstruct the digits in non‑decreasing order to verify the sortable condition. This runs in O(n · d) time with constant extra space, making it faster than explicitly sorting digits for every number.
Is Sum of Sortable Integers asked at Google/Amazon/Meta?
Problems involving digit manipulation, sorting checks, and frequency counting appear frequently in interviews at companies like Google, Amazon, and Meta. Variations often test whether candidates recognize when sorting can be replaced by counting or greedy reconstruction.
What data structure is used in Sum of Sortable Integers?
The core data structure is a fixed-size frequency array for digits 0 through 9. This structure allows constant-time updates while scanning digits and enables quick reconstruction of sorted digit sequences.
What is the time complexity of Sum of Sortable Integers?
The optimal solution runs in O(n · d) time where n is the number of integers and d is the number of digits per integer. Using digit frequency counting avoids sorting, which would otherwise cost O(d log d) per number. Space complexity stays O(1) because the digit range is fixed.

Ready to solve this problem?

Practice Sum of Sortable Integers with our built-in code editor and test cases.

Practice on FleetCode