Maximum K to Sort a Permutation
Real-world version: Largest Shared Mask That Still SortsThe statement here is our own: the same inputs, outputs and technique.
A rack holds n trays numbered 0 through n - 1, and nums is a permutation of those numbers giving the label on each tray.
A lifter is set to a whole number k. It may exchange the labels in two trays only when both of those labels carry every bit that k carries, that is when label & k == k for each of them. Exchanges may be made as often as wanted.
Return the largest k for which the lifter can bring the rack into increasing order, so that the label in every tray equals the tray's own number. At least one label starts out in the wrong tray.
Examples
Example 1
- Input
- nums = [0, 1, 2, 3, 5, 4]
- Output
- 4
The labels 5 and 4 are the ones in the wrong trays. Both carry the third bit, and 5 also carries the lowest bit while 4 does not, so the bits they share come to 4.
Example 2
- Input
- nums = [2, 3, 0, 1]
- Output
- 0
All four labels are in the wrong trays, and the label 0 carries no bits at all, so the bits shared by every misplaced label come to 0.
Example 3
- Input
- nums = [5, 4, 7, 6, 1, 0, 3, 2]
- Output
- 0
Every label is in the wrong tray, and the label 0 is among them, so no bit is shared by all of them.
Constraints
- 2 <= nums.length <= 10^5
- 0 <= nums[i] <= 99999
- nums is a permutation of the numbers from 0 to nums.length - 1
- At least one label starts in the wrong tray
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def largest_shared_mask(nums: list[int]) -> int:public int largestSharedMask(int[] nums)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 13 test cases: 13 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's