↓Skip to main content
  1. LeetCode/

LeetCode 3644: Maximum K to Sort a Permutation

·2 mins· ·
LeetCode Medium Bit-Manipulation Array
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2025-08-10

  • Submissions: Wrong Answer → Accepted

Approach
#

Swapping nums[i] and nums[j] requires nums[i] & nums[j] == k, so every number that takes part in a swap contains all of k’s bits (Bit Manipulation Template 1).

  • Each misplaced number must be swapped at least once, so every bit of k must belong to all of them: k is at most their combined AND.
  • That value is achievable: k itself is in the array (values are 0..n-1, and k is no larger than any misplaced number), and k & x == k for every misplaced x, so k can serve as a pivot that every swap goes through, fixing each cycle.
  • If the array is already sorted, return 0.

My Attempts
#

Attempt 1 tried simulating: for each misplaced position i, take the maximum of i & nums[i] and swap the right number in. But k is a single value that must let all misplaced numbers swap, so a maximum is wrong. For [2, 3, 0, 1] all four move and 2 & 3 & 0 & 1 = 0, so the answer is 0; it returned 1. ANDing them all passed.

Solution
#

class Solution:
    def sortPermutation(self, nums: List[int]) -> int:
        k = -1                                     # -1 的每一位都是 1
        for i, x in enumerate(nums):
            if x != i:
                k &= x
        return 0 if k == -1 else k

Complexity
#

Time O(n), space O(1).

Mistakes to Avoid
#

  • k must let every misplaced number swap, so it is an AND, not a per-position maximum.
  • AND starts from -1 (all bits set), not 0.

Interview Explanation
#

Every misplaced number must take part in a swap, and swapped pairs AND to k, so all of them contain k’s bits. The largest k is the AND of all misplaced numbers, or 0 if already sorted. Time O(n).

Related

LeetCode 473: Matchsticks to Square
·2 mins
LeetCode Medium Array Dynamic-Programming Backtracking Bit-Manipulation
LeetCode 473 note: the total must be divisible by 4; place sticks from longest to shortest into one of four sides, skipping a side that would overflow or that equals a side already tried
LeetCode 137: Single Number II
·2 mins
LeetCode Medium Array Bit-Manipulation
LeetCode 137 note: with everything else appearing three times, count the 1s at each bit modulo 3; the leftover bits form the answer, minding negatives
LeetCode 287: Find the Duplicate Number
·2 mins
LeetCode Medium Array Two-Pointers Binary-Search Bit-Manipulation
LeetCode 287 note: treat i -> nums[i] as a linked list; the duplicate is the cycle entry, found with Floyd’s algorithm in O(1) space without modifying the array
LeetCode 78: Subsets
·1 min
LeetCode Medium Array Backtracking Bit-Manipulation
LeetCode 78 note: each element is either taken or not; iteratively, each new number copies every existing subset with the number appended
LeetCode 90: Subsets II
·2 mins
LeetCode Medium Array Backtracking Bit-Manipulation
LeetCode 90 note: sort first; for a number equal to the previous one, extend only the subsets created in the previous step
LeetCode 3638: Maximum Balanced Shipments
·2 mins
LeetCode Medium Dynamic-Programming Greedy Monotonic-Stack Array
LeetCode 3638 note: greedily cut a segment as soon as a value below its maximum appears; until then the segment is non-decreasing, so its maximum is the previous value