Monday, November 18, 2024
Google search engine
HomeData Modelling & AIMinimize swaps required to maximize the count of elements replacing a greater...

Minimize swaps required to maximize the count of elements replacing a greater element in an Array

Given an array A[], consisting of N elements, the task is to find the minimum number of swaps required such that array elements swapped to replace a higher element, in the original array, are maximized.

Examples:

Input: A[] = {4, 3, 3, 2, 5} 
Output:
Explanation: 
Swap 1: {4, 3, 3, 2, 5} -> {5, 3, 3, 2, 4
Swap 2: {5, 3, 3, 2, 4} -> {3, 3, 5, 2, 4} 
Swap 3: {3, 3, 5, 2, 4} -> {3, 3, 2, 5, 4} 
Therefore, elements {4, 3, 2} occupies original position of a higher element after swapping
Input:. A[] = {6, 5, 4, 3, 2, 1} 
Output: 5

Naive Approach: The simplest approach to solve the problem can be implemented as follows:

  • Sort the array in ascending order.
  • Initialize two variables, result, and index, to store the count and the index up to which it has been considered in the original array, respectively.
  • Iterate over the array elements. For any element A[i], go to a value in the array which is greater than ai and increment the index variable accordingly.
  • After finding an element greater than A[i], increment result, and index.
  • If the index has reached the end of the array, no elements are left to be swapped with previously checked elements.
  • Therefore, print count.

Below is the implementation of the above approach: 

C++




// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the minimum
// number of swaps required
int countSwaps(int A[], int n)
{
    // Sort the array in ascending order
    sort(A, A + n);
 
    int ind = 1, res = 0;
 
    for (int i = 0; i < n; i++) {
 
        // Iterate until a greater element
        // is found
        while (ind < n and A[ind] == A[i])
 
            // Keep incrementing ind
            ind++;
 
        // If a greater element is found
        if (ind < n and A[ind] > A[i]) {
 
            // Increase count of swap
            res++;
 
            // Increment ind
            ind++;
        }
 
        // If end of array is reached
        if (ind >= n)
            break;
    }
 
    // Return the answer
    return res;
}
 
// Driver Code
int main()
{
 
    int A[] = { 4, 3, 3, 2, 5 };
    cout << countSwaps(A, 5);
 
    return 0;
}


Java




// Java Program to implement
// the above approach
import java.util.*;
class GFG{
 
// Function to find the minimum
// number of swaps required
static int countSwaps(int A[], int n)
{
    // Sort the array in ascending order
    Arrays.sort(A);
    int ind = 1, res = 0;
 
    for (int i = 0; i < n; i++)
    {
 
        // Iterate until a greater element
        // is found
        while (ind < n && A[ind] == A[i])
 
            // Keep incrementing ind
            ind++;
 
        // If a greater element is found
        if (ind < n && A[ind] > A[i])
        {
 
            // Increase count of swap
            res++;
 
            // Increment ind
            ind++;
        }
 
        // If end of array is reached
        if (ind >= n)
            break;
    }
 
    // Return the answer
    return res;
}
 
// Driver Code
public static void main(String[] args)
{
    int A[] = { 4, 3, 3, 2, 5 };
    System.out.print(countSwaps(A, 5));
}
}
 
// This code is contributed by gauravrajput1


Python3




# Python3 program to implement
# the above approach
 
# Function to find the minimum
# number of swaps required
def countSwaps(A, n):
 
    # Sort the array in ascending order
    A.sort()
 
    ind, res = 1, 0
 
    for i in range(n):
 
        # Iterate until a greater element
        # is found
        while (ind < n and A[ind] == A[i]):
 
            # Keep incrementing ind
            ind += 1
 
        # If a greater element is found
        if (ind < n and A[ind] > A[i]):
 
            # Increase count of swap
            res += 1
 
            # Increment ind
            ind += 1
 
        # If end of array is reached
        if (ind >= n):
            break
 
    # Return the answer
    return res
 
# Driver Code
A = [ 4, 3, 3, 2, 5 ]
 
print (countSwaps(A, 5))
 
# This code is contributed by chitranayal


C#




// C# Program to implement
// the above approach
using System;
class GFG{
 
// Function to find the minimum
// number of swaps required
static int countSwaps(int []A, int n)
{
    // Sort the array in ascending order
    Array.Sort(A);
    int ind = 1, res = 0;
 
    for (int i = 0; i < n; i++)
    {
 
        // Iterate until a greater element
        // is found
        while (ind < n && A[ind] == A[i])
 
            // Keep incrementing ind
            ind++;
 
        // If a greater element is found
        if (ind < n && A[ind] > A[i])
        {
 
            // Increase count of swap
            res++;
 
            // Increment ind
            ind++;
        }
 
        // If end of array is reached
        if (ind >= n)
            break;
    }
 
    // Return the answer
    return res;
}
 
// Driver Code
public static void Main(String[] args)
{
    int []A = { 4, 3, 3, 2, 5 };
    Console.Write(countSwaps(A, 5));
}
}
 
// This code is contributed by Amit Katiyar


Javascript




<script>
// JavaScript program for the above approach
 
// Function to find the minimum
// number of swaps required
function countSwaps(A, n)
{
    // Sort the array in ascending order
    A.sort();
    let ind = 1, res = 0;
  
    for (let i = 0; i < n; i++)
    {
  
        // Iterate until a greater element
        // is found
        while (ind < n && A[ind] == A[i])
  
            // Keep incrementing ind
            ind++;
  
        // If a greater element is found
        if (ind < n && A[ind] > A[i])
        {
  
            // Increase count of swap
            res++;
  
            // Increment ind
            ind++;
        }
  
        // If end of array is reached
        if (ind >= n)
            break;
    }
  
    // Return the answer
    return res;
}
     
// Driver Code
 
    let A = [ 4, 3, 3, 2, 5 ];
    document.write(countSwaps(A, 5));
              
</script>


Output: 

3

Time Complexity: O(N * log N) 
Auxiliary Space: O(1)

Efficient Approach: 
Since any swap between two unequal elements leads to an element replacing a higher element, it can be observed that the minimum number of swaps required is N – (the maximum frequency of an array element). Therefore, find the most frequent element in the array using HashMap, and print the result.

Below is the implementation of the above approach: 

C++




// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the minimum
// number of swaps required
int countSwaps(int A[], int n)
{
    // Stores the frequency of the
    // array elements
    map<int, int> mp;
 
    // Stores maximum frequency
    int max_frequency = 0;
 
    // Find the max frequency
    for (int i = 0; i < n; i++) {
 
        // Update frequency
        mp[A[i]]++;
 
        // Update maximum frequency
        max_frequency
            = max(max_frequency, mp[A[i]]);
    }
 
    return n - max_frequency;
}
 
// Driver Code
int main()
{
 
    int A[] = { 6, 5, 4, 3, 2, 1 };
 
    // function call
    cout << countSwaps(A, 6);
 
    return 0;
}


Java




// Java Program to implement
// the above approach
import java.util.*;
class GFG{
 
// Function to find the minimum
// number of swaps required
static int countSwaps(int arr[], int n)
{
    // Stores the frequency of the
    // array elements
    HashMap<Integer,
              Integer> mp = new HashMap<Integer,
                                        Integer>();
 
    // Stores maximum frequency
    int max_frequency = 0;
 
    // Find the max frequency
    for (int i = 0; i < n; i++)
    {
 
        // Update frequency
        if(mp.containsKey(arr[i]))
        {
            mp.put(arr[i], mp.get(arr[i]) + 1);
        }
        else
        {
            mp.put(arr[i], 1);
        }
 
        // Update maximum frequency
        max_frequency = Math.max(max_frequency,
                                 mp.get(arr[i]));
    }
    return n - max_frequency;
}
 
// Driver Code
public static void main(String[] args)
{
    int A[] = { 6, 5, 4, 3, 2, 1 };
 
    // function call
    System.out.print(countSwaps(A, 6));
}
}
 
// This code is contributed by Rohit_ranjan


Python3




# Python3 Program to implement
# the above approach
 
# Function to find the minimum
# number of swaps required
def countSwaps(A, n):
     
    # Stores the frequency of the
    # array elements
    mp = {}
 
    # Stores maximum frequency
    max_frequency = 0
 
    # Find the max frequency
    for i in range(n):
 
        # Update frequency
        if A[i] in mp:
            mp[A[i]] += 1
        else:
            mp[A[i]] = 1
 
        # Update maximum frequency
        max_frequency = max(max_frequency,
                            mp[A[i]])
 
    return n - max_frequency
   
# Driver code
if __name__ == "__main__":   
 
      A = [6, 5, 4, 3, 2, 1]
     
    # function call
    print(countSwaps(A, 6))
 
# This code is contributed by divyeshrabadiya07


C#




// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find the minimum
// number of swaps required
static int countSwaps(int []arr, int n)
{
     
    // Stores the frequency of the
    // array elements
    Dictionary<int,
               int> mp = new Dictionary<int,
                                        int>();
 
    // Stores maximum frequency
    int max_frequency = 0;
 
    // Find the max frequency
    for(int i = 0; i < n; i++)
    {
         
        // Update frequency
        if(mp.ContainsKey(arr[i]))
        {
            mp[arr[i]] = mp[arr[i]] + 1;
        }
        else
        {
            mp.Add(arr[i], 1);
        }
 
        // Update maximum frequency
        max_frequency = Math.Max(max_frequency,
                                 mp[arr[i]]);
    }
    return n - max_frequency;
}
 
// Driver Code
public static void Main(String[] args)
{
    int []A = { 6, 5, 4, 3, 2, 1 };
 
    // Function call
    Console.Write(countSwaps(A, 6));
}
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
 
// Javascript Program to implement
// the above approach
 
// Function to find the minimum
// number of swaps required
function countSwaps(A, n)
{
    // Stores the frequency of the
    // array elements
    var mp = new Map();
 
    // Stores maximum frequency
    var max_frequency = 0;
 
    // Find the max frequency
    for (var i = 0; i < n; i++) {
 
        // Update frequency
        if(mp.has(A[i]))
            mp.set(A[i], mp.get(A[i])+1)
        else
            mp.set(A[i], 1);
 
        // Update maximum frequency
        max_frequency
            = Math.max(max_frequency, mp.get(A[i]));
    }
 
    return n - max_frequency;
}
 
// Driver Code
var A = [6, 5, 4, 3, 2, 1 ];
// function call
document.write( countSwaps(A, 6));
 
</script>   


Output: 

5

Time Complexity: O(N) 
Auxiliary Space: O(N)

Using Using Hash Map in python:

Approach:

In this approach, a hash map can be used to store the original position of each element. The array can be sorted and the number of swaps required can be counted. While swapping, the original position of the swapped elements can be updated in the hash map. Finally, the number of elements that occupy the original position of a higher element after swapping can be counted using the hash map.

Create a dictionary with the value as the key and index as the value.
Sort the array.
Loop through the array, and for each element that is not in the correct position, swap it with the element that should be in its place, and update the dictionary accordingly. Keep track of the number of swaps performed.
Count the number of elements that replace a greater element after sorting the array.

Python3




def count_swaps(arr):
    n = len(arr)
    position = {arr[i]: i for i in range(n)} # create a dictionary with the value as key and index as value
    arr.sort() # sort the array
    swaps = 0
    for i in range(n):
        if position[arr[i]] != i: # if the current element is not in the correct position
            position[arr[i]], position[arr[position[arr[i]]]] = position[arr[position[arr[i]]]], position[arr[i]] # swap the elements
            swaps += 1
    count = 0
    for i in range(n-1):
        if arr[i] < arr[i+1]: # count the number of elements which replace a greater element after sorting
            count += 1
    return count, swaps
 
# Example usage:
arr1 = [4, 3, 3, 2, 5]
arr2 = [6, 5, 4, 3, 2, 1]
count1, swaps1 = count_swaps(arr1)
count2, swaps2 = count_swaps(arr2)
print("Input: A[] = {}".format(arr1))
print("Output: {}".format(count1))
print("Number of swaps required: {}".format(swaps1))
print("Input: A[] = {}".format(arr2))
print("Output: {}".format(count2))
print("Number of swaps required: {}".format(swaps2))


Output

Input: A[] = [2, 3, 3, 4, 5]
Output: 3
Number of swaps required: 3
Input: A[] = [1, 2, 3, 4, 5, 6]
Output: 5
Number of swaps required: 6

This approach has a time complexity of O(nlogn)

And an auxiliary space of O(n).

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments