Given two arrays arr[] and brr[] of length N, the task is to find the minimum number of swaps of the same indexed elements required such an element occurs at least half of the indices in the array arr[], i.e. Majority element. If it is not possible to obtain such an arrangement, then print “-1”.
Examples:
Input: arr[] = {3, 2, 1, 4, 9}, brr[] = {5, 5, 3, 5, 3}
Output: 2
Explanation:
Following are the swaps required:
Swap 1: Swapping arr[1] and brr[1] modifies arr[] to {3, 2, 3, 4, 9} and brr[] to {5, 5, 1, 5, 3}.
Swap 2: Swapping arr[5] and brr[5] modifies arr[] to {3, 2, 3, 4, 3} and brr[] to {5, 5, 1, 5, 9}.
Therefore, the total number of swaps required is 2.
Input: arr[] = {2, 4, 2}, brr[] = {1, 2, 9}
Output: 0
Approach: Follow the steps below to solve the above problem:
- Initialize a variable res as INT_MAX that stores the minimum swap required.
- Find the frequency count of arrays a[] and b[] elements using hashing and store it in the map A and B respectively.
- Create an array, crr[] of size 2*N to store all elements from the array arr[] and brr[].
- Traverse the array crr[] using the variable i and do the following:
- If the frequency of crr[i] in map A is at least N/2 then the minimum swap required is 0 and break out of the loop and print 0.
- If the sum of the frequency of crr[i] in maps A and B is at least N/2 then update res to the minimum of res and (N/2 – A[crr[i]]).
- After the above steps, if the value of res is still INT_MAX, then print “-1”.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minMoves( int a[], int b[], int n)
{
unordered_map< int , int > A, B;
vector< int > c;
int maxOccur = ceil ( floor (n)
/ (2 * 1.0));
for ( int i = 0; i < n; ++i) {
c.push_back(a[i]);
c.push_back(b[i]);
A[a[i]]++;
if (b[i] != a[i]) {
B[b[i]]++;
}
}
int res = INT_MAX;
for ( int i = 0; i < c.size(); ++i) {
int x = A];
int y = B];
if ((x + y) >= maxOccur) {
if (x >= maxOccur) {
return 0;
}
else {
res = min(res, maxOccur - x);
}
}
}
if (res == INT_MAX) {
return -1;
}
else
return res;
}
int main()
{
int arr[] = { 3, 2, 1, 4, 9 };
int brr[] = { 5, 5, 3, 5, 3 };
int N = sizeof (arr) / sizeof (arr[0]);
cout << minMoves(arr, brr, N);
return 0;
}
|
Java
import java.util.*;
class Main{
public static int minMoves( int a[],
int b[],
int n)
{
HashMap<Integer,
Integer> A =
new HashMap<>();
HashMap<Integer,
Integer> B =
new HashMap<>();
Vector<Integer> c =
new Vector<Integer>();
int maxOccur = ( int )Math.ceil(
( int )Math.floor(n) /
( 2 * 1.0 ));
for ( int i = 0 ; i < n; ++i)
{
c.add(a[i]);
c.add(b[i]);
if (A.containsKey(a[i]))
{
A.replace(a[i],
A.get(a[i]) + 1 );
}
else
{
A.put(a[i], 1 );
}
if (b[i] != a[i])
{
if (B.containsKey(b[i]))
{
B.replace(b[i],
B.get(b[i]) + 1 );
}
else
{
B.put(b[i], 1 );
}
}
}
int res = Integer.MAX_VALUE;
for ( int i = 0 ; i < c.size(); ++i)
{
int x = 0 ;
if (A.containsKey(c.get(i)))
{
x = A.get(c.get(i));
}
int y = 0 ;
if (B.containsKey(c.get(i)))
{
y = B.get(c.get(i));
}
if ((x + y) >= maxOccur)
{
if (x >= maxOccur)
{
return 0 ;
}
else
{
res = Math.min(res,
maxOccur - x);
}
}
}
if (res == Integer.MAX_VALUE)
{
return - 1 ;
}
else
return res;
}
public static void main(String[] args)
{
int arr[] = { 3 , 2 , 1 , 4 , 9 };
int brr[] = { 5 , 5 , 3 , 5 , 3 };
int N = arr.length;
System.out.println(minMoves(arr, brr, N));
}
}
|
Python3
from math import ceil, floor
import sys
def minMoves(a, b, n):
A, B = {}, {}
c = []
maxOccur = ceil(floor(n) / ( 2 * 1.0 ))
for i in range (n):
c.append(a[i])
c.append(b[i])
A[a[i]] = A.get(a[i], 0 ) + 1
if (b[i] ! = a[i]):
B[b[i]] = B.get(b[i], 0 ) + 1
res = sys.maxsize
for i in range ( len (c)):
x, y = 0 , 0
if c[i] in A:
x = A]
if c[i] in B:
y = B]
if ((x + y) > = maxOccur):
if (x > = maxOccur):
return 0
else :
res = min (res, maxOccur - x)
if (res = = sys.maxsize):
return - 1
else :
return res
if __name__ = = '__main__' :
arr = [ 3 , 2 , 1 , 4 , 9 ]
brr = [ 5 , 5 , 3 , 5 , 3 ]
N = len (arr)
print (minMoves(arr, brr, N))
|
C#
using System;
using System.Collections.Generic;
class GFG{
public static int minMoves( int []a,
int []b,
int n)
{
Dictionary< int ,
int > A = new Dictionary< int ,
int >();
Dictionary< int ,
int > B = new Dictionary< int ,
int >();
List< int > c = new List< int >();
int maxOccur = ( int )(Math.Ceiling(
( int )(Math.Floor(
( double )n)) / (2 * 1.0)));
for ( int i = 0; i < n; ++i)
{
c.Add(a[i]);
c.Add(b[i]);
if (A.ContainsKey(a[i]))
{
A[a[i]] = A[a[i]] + 1;
}
else
{
A.Add(a[i], 1);
}
if (b[i] != a[i])
{
if (B.ContainsKey(b[i]))
{
B[b[i]]++;
}
else
{
B.Add(b[i], 1);
}
}
}
int res = int .MaxValue;
for ( int i = 0; i < c.Count; ++i)
{
int x = 0;
if (A.ContainsKey(c[i]))
{
x = A];
}
int y = 0;
if (B.ContainsKey(c[i]))
{
y = B];
}
if ((x + y) >= maxOccur)
{
if (x >= maxOccur)
{
return 0;
}
else
{
res = Math.Min(res,
maxOccur - x);
}
}
}
if (res == int .MaxValue)
{
return -1;
}
else
return res;
}
public static void Main(String[] args)
{
int []arr = { 3, 2, 1, 4, 9 };
int []brr = { 5, 5, 3, 5, 3 };
int N = arr.Length;
Console.WriteLine(minMoves(arr, brr, N));
}
}
|
Javascript
<script>
function minMoves(a, b, n)
{
var A = new Map(), B = new Map();
var c = [];
var maxOccur = Math.ceil(Math.floor(n)
/ (2 * 1.0));
for ( var i = 0; i < n; ++i) {
c.push(a[i]);
c.push(b[i]);
if (A.has(a[i]))
{
A.set(a[i], A.get(a[i])+1);
}
else
{
A.set(a[i], 1);
}
if (b[i] != a[i]) {
if (B.has(b[i]))
{
B.set(b[i], B.get(b[i])+1);
}
else
{
B.set(b[i], 1);
}
}
}
var res = 1000000000;
for ( var i = 0; i < c.length; ++i) {
var x = A.get(c[i]);
var y = B.get(c[i]);
if ((x + y) >= maxOccur) {
if (x >= maxOccur) {
return 0;
}
else {
res = Math.min(res, maxOccur - x);
}
}
}
if (res == 1000000000) {
return -1;
}
else
return res;
}
var arr = [3, 2, 1, 4, 9];
var brr = [5, 5, 3, 5, 3];
var N = arr.length;
document.write( minMoves(arr, brr, N));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)