CF BUDDY
← Problems·

1954B · Make It Ugly

1200 · implementation, math

Problem: Let's call an array aa beautiful if you can make all its elements the same by using the following operation an arbitrary number of times (possibly, zero):

  • choose an index ii (2ia12 \le i \le |a| - 1) such that ai1=ai+1a_{i - 1} = a_{i + 1}, and replace aia_i with ai1a_{i - 1}.

You are given a beautiful array a1,a2,,ana_1, a_2, \dots, a_n. What is the minimum number of elements you have to remove from it in order for it to stop being beautiful? Swapping elements is prohibited. If it is impossible to do so, then output -1.

Input Format: The first line contains a single integer tt (1t1041 \le t \le 10^4) — the number of test cases.

The first line of each test case contains a single integer nn (1n31051 \le n \le 3 \cdot 10^5).

The second line contains nn integers a1,a2,,ana_1, a_2, \dots, a_n (1ain1 \le a_i \le n).

Additional constraints on the input:

  • in every test case, the given array aa is beautiful;
  • the sum of nn over all test cases does not exceed 31053 \cdot 10^5.

Output Format: For each test case, output a single integer — the minimum number of elements you have to remove from the array aa in order for it to stop being beautiful. If it is impossible, then output -1.

Note: In the first testcase, it is impossible to modify the array in such a way that it stops being beautiful. An array consisting of identical numbers will remain beautiful no matter how many numbers we remove from it.

In the second testcase, you can remove the number at the index 55, for example.

The resulting array will be [1,2,1,2][1, 2, 1, 2]. Let's check if it is beautiful. Two operations are available:

  • Choose i=2i = 2: the array becomes [1,1,1,2][1, 1, 1, 2]. No more operations can be applied to it, and the numbers are not all the same.
  • Choose i=3i = 3 instead: the array becomes [1,2,2,2][1, 2, 2, 2]. No more operations can be applied to it either, and the numbers are still not all the same.

Thus, the array [1,2,1,2][1, 2, 1, 2] is not beautiful.

In the fourth testcase, you can remove the first three elements, for example. The resulting array [5,3,3,3][5, 3, 3, 3] is not beautiful.

Sample Cases

Case 1

Input

4
3
2 2 2
5
1 2 1 2 1
1
1
7
3 3 3 5 3 3 3

Output

-1
1
-1
3

Similar problems

00:00:00
Loading editor…
Welcome! I'm your coding tutor for this problem. Use the chips below to reveal stored hints or get AI feedback on your code. I'll guide you step by step — never giving away the solution.

Sign in to unlock AI tutor feedback