Minimum Number of Swaps Required to Arrange Pairs Adjacent to Each Other

There are n pairs and therefore 2n people. Everyone has one unique number ranging in 1..2n. All these 2n persons are arranged in random fashion in an array of size 2n. We are also given who is partner of whom. Find the minimum number of swaps required to arrange these pairs such that all pairs become adjacent to each other.

Example:

pairs = [1, 3, 2, 6, 4, 5] means 1 is partner of 3 and so on. For arr = [3, 5, 6, 4, 1, 2], the output should be 2.

Because, we can get [3, 1, 5, 4, 6, 2] by swapping 5 with 6, and 6 with 1.

Contributed by Berkan Teber