All problems
0863MediumArrayBit Manipulation

Largest Shared Mask That Still Sorts

Tracked in this browser only
Write code

Trains the technique from

LeetCode 3644Maximum K to Sort a Permutation

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def largest_shared_mask(nums: list[int]) -> int:
Java
public int largestSharedMask(int[] nums)
September 7
Apply