Open In App

Replace each element by the difference of the total size of the array and frequency of that element

Given an array of integers, the task is to replace every element by the difference of the total size of the array and its frequency.

Examples: 

Input: arr[] = { 1, 2, 5, 2, 2, 5, 4 }
Output: 6 4 5 4 4 5 6
Explanation:
Size of the array is 7.
The frequency of 1 is 1. So replace it by 7-1 = 6
The frequency of 2 is 3. So replace it by 7-3 = 4

Input: arr[] = { 4, 5, 4, 5, 6, 6, 6 }
Output: 5 5 5 5 4 4 4

Approach: 

  1. Take a hash map, which will store the frequency of all the elements in the array.
  2. Now, traverse once again.
  3. Now, replace all the elements by the difference of the total size of the array and its frequency.
  4. Print the modified array.

Below is the implementation of the above approach:  

// C++ program to Replace each element
// by the difference of the total size
// of the array and its frequency
#include <bits/stdc++.h>
using namespace std;

// Function to replace the elements
void ReplaceElements(int arr[], int n)
{
    // Hash map which will store the
    // frequency of the elements of the array.
    unordered_map<int, int> mp;

    for (int i = 0; i < n; ++i) 

        // Increment the frequency
        // of the element by 1.
        mp[arr[i]]++;
    

    // Replace every element by its frequency
    for (int i = 0; i < n; ++i) 
        arr[i] = n - mp[arr[i]];

}

// Driver code
int main()
{
    int arr[] = { 1, 2, 5, 2, 2, 5, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);

    ReplaceElements(arr, n);

    // Print the modified array.
    for (int i = 0; i < n; ++i)
        cout << arr[i] << " ";

    return 0;
}
// Java program to Replace each element
// by the difference of the total size
// of the array and its frequency
import java.util.*;

class GFG
{

    // Function to replace the elements
    static void ReplaceElements(int arr[], int n) 
    {
        // Hash map which will store the
        // frequency of the elements of the array.
        HashMap<Integer, Integer> mp = new HashMap<>();

        for (int i = 0; i < n; i++) 
        {

            // Increment the frequency
            // of the element by 1.
            if (!mp.containsKey(arr[i])) 
            {
                mp.put(arr[i], 1);
            } 
            else 
            {
                mp.put(arr[i], mp.get(arr[i]) + 1);
            }
        }

        // Replace every element by its frequency
        for (int i = 0; i < n; ++i) 
        {
            arr[i] = n - mp.get(arr[i]);
        }

    }

    // Driver code
    public static void main(String[] args) 
    {
        int arr[] = {1, 2, 5, 2, 2, 5, 4};
        int n = arr.length;

        ReplaceElements(arr, n);

        // Print the modified array.
        for (int i = 0; i < n; ++i)
        {
            System.out.print(arr[i] + " ");
        }
    }
}

// This code contributed by Rajput-Ji
# Python3 program to Replace each element
# by the difference of the total size
# of the array and its frequency

# Function to replace the elements
def ReplaceElements(arr, n):
    
    # Hash map which will store the
    # frequency of the elements of the array.
    mp = dict()

    for i in range(n):
        
        # Increment the frequency
        # of the element by 1.
        mp[arr[i]] = mp.get(arr[i], 0) + 1

    # Replace every element by its frequency
    for i in range(n):
        arr[i] = n - mp[arr[i]]

# Driver code
arr = [1, 2, 5, 2, 2, 5, 4]
n = len(arr)

ReplaceElements(arr, n)

# Print the modified array.
for i in range(n):
    print(arr[i], end = " ")

# This code is contributed by mohit kumar
// C# program to Replace each element
// by the difference of the total size
// of the array and its frequency
using System;
using System.Collections.Generic; 

class GFG
{

    // Function to replace the elements
    static void ReplaceElements(int []arr, int n) 
    {
        // Hash map which will store the
        // frequency of the elements of the array.
        Dictionary<int,int> mp = new Dictionary<int,int>();

        for (int i = 0; i < n; i++) 
        {

            // Increment the frequency
            // of the element by 1.
            if (!mp.ContainsKey(arr[i])) 
            {
                mp.Add(arr[i], 1);
            } 
            else
            {
                var a = mp[arr[i]] + 1;
                mp.Remove(arr[i]);
                mp.Add(arr[i], a);
            }
        }

        // Replace every element by its frequency
        for (int i = 0; i < n; ++i) 
        {
            arr[i] = n - mp[arr[i]];
        }

    }

    // Driver code
    public static void Main() 
    {
        int []arr = {1, 2, 5, 2, 2, 5, 4};
        int n = arr.Length;

        ReplaceElements(arr, n);

        // Print the modified array.
        for (int i = 0; i < n; ++i)
        {
            Console.Write(arr[i] + " ");
        }
    }
}

/* This code contributed by PrinciRaj1992 */
// JavaScript program to Replace each element
// by the difference of the total size
// of the array and its frequency

// Function to replace the elements
function ReplaceElements(arr, n) 
{
    
    // Hash map which will store the
    // frequency of the elements of the array.
    let mp = new Map();

    for(let i = 0; i < n; i++) 
    {
        
        // Increment the frequency
        // of the element by 1.
        if (!mp.has(arr[i])) 
        {
            mp.set(arr[i], 1);
        } 
        else 
        {
            mp.set(arr[i], mp.get(arr[i]) + 1);
        }
    }

    // Replace every element by its frequency
    for(let i = 0; i < n; ++i) 
    {
        arr[i] = n - mp.get(arr[i]);
    }
}

// Driver Code
let arr = [ 1, 2, 5, 2, 2, 5, 4 ];
let n = arr.length;

ReplaceElements(arr, n);

// Print the modified array.
for(let i = 0; i < n; ++i)
{
    console.log(arr[i] + " ");
}

// This code is contributed by code_hunt

Output
6 4 5 4 4 5 6 

Time Complexity: O(N) where N is traversing all elements in the array.
Auxiliary Space: O(N) where N is for map to store the frequency of array elements.

Approach : Sorting

Steps of Approach :

Below is the implementation of the above approach:  

#include <iostream>
#include <vector>
#include <algorithm>
#include <sstream>

std::string replace_with_difference(std::vector<int>& arr) {
    // Step 1: Sort the array
    std::sort(arr.begin(), arr.end());
    
    // Initialize variables
    int n = arr.size();
    int count = 1; // Initialize count for the first element
    std::ostringstream result;
    
    // Iterate through the sorted array and replace elements
    for (int i = 1; i < n; ++i) {
        if (arr[i] == arr[i - 1]) {
            count++;
        } else {
            for (int j = 0; j < count; ++j) {
                result << n - count << " ";
            }
            count = 1; // Reset count for the new element
        }
    }

    // Handle the last element
    for (int j = 0; j < count; ++j) {
        result << n - count << " ";
    }

    return result.str(); // Convert stringstream to string
}

int main() {
    std::vector<int> arr1 = {1, 2, 5, 2, 2, 5, 4};
    std::vector<int> arr2 = {4, 5, 4, 5, 6, 6, 6};

    std::cout << replace_with_difference(arr1) << std::endl;
    
    return 0;
}
// Java Code
import java.util.Arrays;

public class GFG{
    
    public static String replaceWithDifference(int[] arr) {
        // Step 1: Sort the array
        Arrays.sort(arr);
        
        // Initialize variables
        int n = arr.length;
        int count = 1; // Initialize count for the first element
        StringBuilder result = new StringBuilder();
        
        // Iterate through the sorted array and replace elements
        for (int i = 1; i < n; ++i) {
            if (arr[i] == arr[i - 1]) {
                count++;
            } else {
                for (int j = 0; j < count; ++j) {
                    result.append(n - count).append(" ");
                }
                count = 1; // Reset count for the new element
            }
        }

        // Handle the last element
        for (int j = 0; j < count; ++j) {
            result.append(n - count).append(" ");
        }

        return result.toString(); // Convert StringBuilder to string
    }

    public static void main(String[] args) {
        int[] arr1 = {1, 2, 5, 2, 2, 5, 4};
        int[] arr2 = {4, 5, 4, 5, 6, 6, 6};

        System.out.println(replaceWithDifference(arr1));
    }
}

// This code is contributed by guptapratik
def replace_with_difference(arr):
    # Step 1: Sort the array
    arr.sort()
    
    # Initialize variables
    n = len(arr)
    count = 1  # Initialize count for the first element
    result = ""
    
    # Iterate through the sorted array and replace elements
    for i in range(1, n):
        if arr[i] == arr[i-1]:
            count += 1
        else:
            result += " " + " ".join([str(n - count)] * count)  # Replace element with the difference
            count = 1  # Reset count for the new element
    
    # Handle the last element
    result += " " + " ".join([str(n - count)] * count)
    
    return result.strip()  # Remove leading/trailing spaces

arr1 = [1, 2, 5, 2, 2, 5, 4]
arr2 = [4, 5, 4, 5, 6, 6, 6]

print(replace_with_difference(arr1))
function replaceWithDifference(arr) {
    // Step 1: Sort the array
    arr.sort((a, b) => a - b);
    
    // Initialize variables
    const n = arr.length;
    let count = 1;  // Initialize count for the first element
    let result = "";
    
    // Iterate through the sorted array and replace elements
    for (let i = 1; i < n; i++) {
        if (arr[i] === arr[i - 1]) {
            count++;
        } else {
            result += " " + Array(count).fill(n - count).join(" ");  // Replace element with the difference
            count = 1;  // Reset count for the new element
        }
    }
    
    // Handle the last element
    result += " " + Array(count).fill(n - count).join(" ");
    
    return result.trim();  // Remove leading/trailing spaces
}

const arr1 = [1, 2, 5, 2, 2, 5, 4];
const arr2 = [4, 5, 4, 5, 6, 6, 6];

console.log(replaceWithDifference(arr1));

Output
6 4 4 4 6 5 5

Complexity Analysis:

Time Complexity : O(n log n), where n is the number of elements in the array.

Auxiliary Complexity : O(n)








Article Tags :