AND Sorting solution codeforces

AND Sorting solution codeforces

You are given a permutation pp of integers from 00 to n1n−1 (each of them occurs exactly once). Initially, the permutation is not sorted (that is, pi>pi+1pi>pi+1 for at least one 1in11≤i≤n−1).

The permutation is called XX-sortable for some non-negative integer XX if it is possible to sort the permutation by performing the operation below some finite number of times:

  • Choose two indices ii and jj (1i<jn)(1≤i such that pi&pj=Xpi&pj=X.
  • Swap pipi and pjpj.

Here && denotes the bitwise AND operation.

Find the maximum value of XX such that pp is XX-sortable. It can be shown that there always exists some value of XX such that pp is XX-sortable.

Input

The input consists of multiple test cases. The first line contains a single integer tt (1t104)(1≤t≤104)  — the number of test cases. Description of test cases follows.

The first line of each test case contains a single integer nn (2n2105)(2≤n≤2⋅105)  — the length of the permutation.

The second line of each test case contains nn integers p1,p2,...,pnp1,p2,…,pn (0pin10≤pi≤n−1, all pipi are distinct)  — the elements of pp. It is guaranteed that pp is not sorted.

It is guaranteed that the sum of nn over all cases does not exceed 21052⋅105.

Output

For each test case output a single integer — the maximum value of XX such that pp is XX-sortable.

Example
input
Copy
4
4
0 1 3 2
2
1 0
7
0 1 2 3 5 6 4
5
0 3 2 1 4
output
Copy
2
0
4
1
Note

In the first test case, the only XX for which the permutation is XX-sortable are X=0X=0 and X=2X=2, maximum of which is 22.

Sorting using X=0X=0:

  • Contestants ranked 1st will win a Apple HomePod mini
  • Contestants ranked 2nd will win a Logitech G903 LIGHTSPEED Gaming Mouse
  • Contestants ranked 3rd ~ 5th will win a LeetCode Backpack
  • Contestants ranked 6th ~ 10th will win a LeetCode water bottle
  • Contestants ranked 11th ~ 20th will win a LeetCode Big O Notebook
  • Swap p1p1 and p4p4p=[2,1,3,0]p=[2,1,3,0].
  • Swap p3p3 and p4p4p=[2,1,0,3]p=[2,1,0,3].
  • Swap p1p1 and p3p3p=[0,1,2,3]p=[0,1,2,3].

Sorting using X=2X=2:

  • Swap p3p3 and p4p4p=[0,1,2,3]p=[0,1,2,3].

In the second test case, we must swap p1p1 and p2p2 which is possible only with X=0X=0.

SOLUTION

Click here

AND Sorting solution codeforces is one of the most asked coding question. This question is repeated in almost every company paper and if you are ready to crack the interviews and the question papers then you must check our website on daily purpose so that you can get the answer of the latest question “AND Sorting solution codeforces”.

Leave a Comment