cswork / OAOpen practice workspace

AmazonOA #62

Get Sorting Factor K

Estimated MediumJudge-ready

Topics (AI-labelled)Bits & Math

You are given a permutation arr of 0 to n−1. After choosing a non-negative integer k, you may only swap two elements satisfying (arr[i] & arr[j]) == k, where & denotes bitwise AND; k stays fixed throughout the sorting process. If the permutation is not yet sorted, find the largest k with which it can be sorted into 0,1,…,n−1. This site specifies: if the input is already sorted, return 0; this convention follows the fixed source explanation and the consistent behavior of three implementations in Python, Java, and C++. When the array is already sorted, zero swaps are valid for every non-negative k, so the literal original problem has no finite maximum; returning 0 is a convention, not a mathematical maximum.

Input

The first line contains n; the second line contains n integers arr[i]. 1≤n≤100000, and arr is exactly a permutation of 0 to n−1. Standard I/O is this site's wrapper and keeps the original constraints in full.

Output

If the array is not yet sorted, output the largest non-negative k that can complete the sort; if it is already sorted, output 0 per the explicit convention.

Example 1

Input:

4
0 3 2 1

Output:

1

Example 2

Input:

4
0 1 2 3

Output:

0

Example 3

Input:

3
1 0 2

Output:

0

Example notes

In the original example [0,3,2,1], 3&1=1, and swapping these two values sorts the array, so the answer is 1. The second example is already sorted, so 0 is output by convention; in the third example the value zero is misplaced, so a swap involving 0 is required and the answer can only be 0.

Editorial

Loading solution…