#3886
Sum of Sortable Integers
HardArrayMathSortingEnumerationHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Instead of checking all rotations, we can directly compare the original array with its sorted version to determine if k is sortable.
⚙️
Algorithm
3 steps- 1Step 1: Sort the original array to get the target sorted version.
- 2Step 2: For each divisor k of n, check if elements in each subarray can match the sorted array.
- 3Step 3: If all subarrays match their corresponding segments in the sorted array, add k to the result.
solution.py9 lines
1def sum_of_sortable_integers(nums):
2 n = len(nums)
3 sorted_nums = sorted(nums)
4 total_sum = 0
5 for k in range(1, n + 1):
6 if n % k == 0:
7 if all(sorted_nums[i:i+k] == sorted(nums[i:i+k]) for i in range(0, n, k)):
8 total_sum += k
9 return total_sumℹ
Complexity note: Sorting takes O(n log n) and checking each subarray takes O(n), leading to an overall linear complexity for each divisor.
- 1Divisors of n dictate possible subarray sizes.
- 2Sorting helps in direct comparison without rotations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.