Maximum K to Sort a Permutation

You are given an integer array nums of length n, where nums is a permutation of the numbers in the range [0..n - 1].

You may swap elements at indices i and j only if nums[i] AND nums[j] == k, where AND denotes the bitwise AND operation and k is a non-negative integer.

Return the maximum value of k such that the array can be sorted in non-decreasing order using any number of such swaps. If nums is already sorted, return 0.

Example 1
Inputnums = [0,3,2,1]
Output1
Choose k = 1; swapping nums[1] = 3 and nums[3] = 1 is allowed since nums[1] AND nums[3] == 1, resulting in [0, 1, 2, 3].
Example 2
Inputnums = [0,1,3,2]
Output2
Choose k = 2; swapping nums[2] = 3 and nums[3] = 2 is allowed since nums[2] AND nums[3] == 2, resulting in [0, 1, 2, 3].

Constraints

  • 1 <= n == nums.length <= 10^5
  • 0 <= nums[i] <= n - 1
  • nums is a permutation of integers from 0 to n - 1.

Asked at 1 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate