Queries to print count of distinct array elements after replacing element at index P by a given element

Given an array arr[] consisting of N integers and 2D array queries[][] consisting of Q queries of the form {p, x}, the task for each query is to replace the element at position p with x and print the count of distinct elements present in the array.

Examples:

Input: Q = 3, arr[] = {2, 2, 5, 5, 4, 6, 3}, queries[][] = {{1, 7}, {6, 8}, {7, 2}}
Output: {6, 6, 5}
Explanation:
The total distinct elements after each query (one-based indexing): 
Query 1: p = 1 and x = 7. Therefore, arr[1] = 7 and arr[] becomes {7, 2, 5, 5, 4, 6, 3}. Hence, distinct elements = 6.
Query 2: p = 6 and x = 8. Therefore, arr[6] = 8 and arr[] becomes {7, 2, 5, 5, 4, 8, 3}. Hence, distinct elements = 6.
Query 3: p = 7 and x = 2. Therefore, arr[7] = 2 and arr[] becomes {7, 2, 5, 5, 4, 8, 2}. Hence, distinct elements = 5.             

Input: Q = 2, arr[] = {1, 1, 1, 1}, queries[][] = {{2, 2}, {3, 3}}
Output: {2, 3}
Explanation:
The total distinct elements after each query (one-based indexing): 
Query 1: p = 2 and x = 2. Therefore, arr[2] = 2 and arr[] becomes {1, 2, 1, 1}. Hence, distinct elements = 2.
Query 2: p = 3 and x = 3. Therefore, arr[3] = 3 and arr[] becomes {1, 2, 3, 1}. Hence, distinct elements = 3.

Naive approach: The simplest approach is to update the given array for each query and insert all the elements of the updated array into a Set. Print the size of the set as the count of distinct array elements.



Below is the implementation of the above approach:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Function to the total number
    // of distinct elements after each
    // query update
    static void Distinct(int arr[], int n,
                         int p, int x)
    {
        // Update the array
        arr[p - 1] = x;
 
        // Store distinct elements
        Set<Integer> set = new HashSet<>();
 
        for (int i = 0; i < n; i++) {
            set.add(arr[i]);
        }
 
        // Print the size
        System.out.print(set.size() + " ");
    }
 
    // Function to print the count of
    // distinct elements for each query
    static void updateArray(
        int arr[], int n,
        int queries[][], int q)
    {
        // Traverse the query
        for (int i = 0; i < q; i++) {
 
            // Function Call to update
            // each query
            Distinct(arr, n, queries[i][0],
                     queries[i][1]);
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given array arr[]
        int[] arr = { 2, 2, 5, 5, 4, 6, 3 };
 
        int N = arr.length;
 
        int Q = 3;
 
        // Given queries
        int queries[][]
            = new int[][] { { 1, 7 },
                            { 6, 8 },
                            { 7, 2 } };
 
        // Function Call
        updateArray(arr, N, queries, Q);
    }
}

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the
// above approach
using System;
using System.Collections.Generic;
class GFG{
 
// Function to the total number
// of distinct elements after each
// query update
static void Distinct(int []arr, int n,
                     int p, int x)
{
  // Update the array
  arr[p - 1] = x;
 
  // Store distinct elements
  HashSet<int> set =
          new HashSet<int>();
 
  for (int i = 0; i < n; i++)
  {
    set.Add(arr[i]);
  }
 
  // Print the size
  Console.Write(set.Count + " ");
}
 
// Function to print the count of
// distinct elements for each query
static void updateArray(int []arr, int n,
                        int [,]queries, int q)
{
  // Traverse the query
  for (int i = 0; i < q; i++)
  {
    // Function Call to update
    // each query
    Distinct(arr, n, queries[i, 0],
             queries[i, 1]);
  }
}
 
// Driver Code
public static void Main(String[] args)
{
  // Given array []arr
  int[] arr = {2, 2, 5, 5,
               4, 6, 3};
 
  int N = arr.Length;
  int Q = 3;
 
  // Given queries
  int [,]queries = new int[,] {{1, 7},
                               {6, 8},
                               {7, 2}};
 
  // Function Call
  updateArray(arr, N, queries, Q);
}
}
 
// This code is contributed by gauravrajput1

chevron_right


Output: 

6 6 5



 

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

Efficient Approach: To optimize the above approach, the idea is to store the frequency of each array element in a Map and then traverse each query and print the size of the map after each update. Follow the below steps to solve the problem:

  • Store the frequency of each element in a Map M.
  • For each query {p, x}, perform the following steps:
    • Decrease the frequency of arr[p] by 1 in the Map M. If its frequency reduces to 0, remove that element from the Map.
    • Update arr[p] = x and increment the frequency of x by 1 in the Map if it is already present. Otherwise, add element x in the Map setting its frequency as 1.
  • For each query in the above steps, print the size of the Map as the count of the distinct array elements.

Below is the implementation of the above approach:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
 
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Function to store the frequency
    // of each element in the Map
    static void store(int arr[], int n,
                      HashMap<Integer,
                              Integer>
                          map)
    {
        for (int i = 0; i < n; i++) {
 
            // Store the frequency of
            // element arr[i]
            if (!map.containsKey(arr[i]))
                map.put(arr[i], 1);
            else
                map.put(arr[i],
                        map.get(arr[i]) + 1);
        }
    }
 
    // Function to update an array and
    // map & to find the distinct elements
    static void Distinct(int arr[], int n,
                         int p, int x,
                         HashMap<Integer,
                                 Integer>
                             map)
    {
 
        // Decrease the element if it
        // was previously present in Map
        map.put(arr[p - 1],
                map.get(arr[p - 1]) - 1);
 
        if (map.get(arr[p - 1]) == 0)
            map.remove(arr[p - 1]);
 
        // Add the new element to map
        if (!map.containsKey(x)) {
            map.put(x, 1);
        }
        else {
            map.put(x, map.get(x) + 1);
        }
 
        // Update the array
        arr[p - 1] = x;
 
        // Print the count of distinct
        // elements
        System.out.print(map.size() + " ");
    }
 
    // Function to count the distinct
    // element after updating each query
    static void updateQuery(
        int arr[], int n,
        int queries[][], int q)
    {
        // Store the elements in map
        HashMap<Integer, Integer> map
            = new HashMap<>();
 
        store(arr, n, map);
 
        for (int i = 0; i < q; i++) {
 
            // Function Call
            Distinct(arr, n, queries[i][0],
                     queries[i][1], map);
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given array arr[]
        int[] arr = { 2, 2, 5, 5, 4, 6, 3 };
 
        int N = arr.length;
        int Q = 3;
 
        // Given Queries
        int queries[][]
            = new int[][] { { 1, 7 },
                            { 6, 8 },
                            { 7, 2 } };
 
        // Function Call
        updateQuery(arr, N, queries, Q);
    }
}

chevron_right


Output: 

6 6 5



 

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : GauravRajput1