Minimum swaps

2.5

15 votes
Algorithms, Basics of Greedy Algorithms, Greedy Algorithms
Problem

You are given a circular array of length N. You want to make the first two elements of the array equal.

Note

  • A circular array is an array that contains elements in such a way that Ai+1 is the next element of Ai,..., A1 is the next element of AN.
  • You can swap any two adjacent elements.

Your task is to determine the minimum number of swapping required to make the first two elements equal.

Example

Consider N = 7 and the circular array as {-1, 3, 4, -3, 3, -1, 2},

First operation, Swap numbers at index 1, 2 to get new array as {3, -1, 4, -3, 3, -1, 2},

Second operation, Swap numbers at index 6, 7 to get new array as {3, -1, 4, -3, 3, 2, -1},

Third operation, Swap numbers at index 1, 7 to get new array as {-1, -1, 4, -3, 3, 2, 3},

Therefore requires three swap operations. (Assuming 1-based indexing).

Function description

Complete the solve function provided in the editor. This function takes the following 2 parameters and returns the minimum number of swapping required:

N: An Integer representing the length of the array.

A: An Array of length N representing the elements of array A

Input format

Note: This is the input format that you must use to provide custom input (available above the Compile and Test button).

  • The first line contains an integer T denoting the number of test cases.
  • For each test case:
    • The first line contains an integer N.
    • The second line contains N space-separated integers.

Output format

For each test case, print the minimum number of swaps required to make the first two elements equal. If you can not perform this, print -1.

Constraints

1T1051N2×105109Ai109

The total sum of N does not exceed 2×105.

Code snippets (also called starter code/boilerplate code)

This question has code snippets for C, CPP, Java, and Python.

Sample Input
3
5
1 1 2 2 3
4
-1 2 2 3
1
1000000000
Sample Output
0
2
-1
Time Limit: 5
Memory Limit: 256
Source Limit:
Explanation

Note: 1-based indexing is used in sample explanation.

The first test: The first two elements are equal

The second test: You swap the first two elements, the new array = {2 -1 2 3}

Then swap the second element with the third element, the new array = {2 2 -1 3}

You require only two swap operations.

The third test: There exists only one element, thus you can not perform that.

Contributers:
Editor Image

?