#3644
Maximum K to Sort a Permutation
MediumArrayBit ManipulationBit ManipulationSorting
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)
The maximum k is the bitwise AND of all elements that are not in their correct position. This ensures that we can swap elements to sort the array.
⚙️
Algorithm
3 steps- 1Step 1: Create a variable to hold the AND result, initialized to all bits set (e.g., ~0).
- 2Step 2: Iterate through nums and compute the AND for elements not in their sorted position.
- 3Step 3: Return the computed AND value.
solution.py7 lines
1def maxK(nums):
2 sorted_nums = sorted(nums)
3 k = ~0
4 for i in range(len(nums)):
5 if nums[i] != sorted_nums[i]:
6 k &= nums[i]
7 return kℹ
Complexity note: Sorting takes O(n log n) and we traverse the array once, leading to O(n log n) overall.
- 1The AND operation restricts which elements can be swapped.
- 2Elements must be in their sorted positions for k to be maximized.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.