Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Graph
  • Practice Graph
  • MCQs on Graph
  • Graph Tutorial
  • Graph Representation
  • Graph Properties
  • Types of Graphs
  • Graph Applications
  • BFS on Graph
  • DFS on Graph
  • Graph VS Tree
  • Transpose Graph
  • Dijkstra's Algorithm
  • Minimum Spanning Tree
  • Prim’s Algorithm
  • Topological Sorting
  • Floyd Warshall Algorithm
  • Strongly Connected Components
  • Advantages & Disadvantages
Open In App
Next Article:
Divide the array into minimum number of sub-arrays having unique elements
Next article icon

Find Number of Unique Elements in an Array After each Query

Last Updated : 21 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given 2d array A[][1] of size N and array Q[][2] of size M representing M queries of type {a, b}. The task for this problem is in each query move all elements from A[a] to A[b] and print the number of unique elements in A[b].

Constraints:

  • 1 <= N, Q <= 105
  • 1 <= A[i] <= 109
  • 1 <= a, b <= N

Examples:

Input: A[][1] = {{1}, {1}, {1}, {2}, {2}, {3}}, Q[][2] = {{1, 2}, {6, 4}, {5, 1}, {3, 6}, {4, 6}}
Output: 1 2 1 1 3
Explanation:

  • For First query {1, 2} move all elements from A[1] to A[2]. A becomes {{}, {1, 1}, {1}, {2}, {2}, {3}}. Number of unique elements in A[2] is 1.
  • For Second query {6, 4} move all elements from A[6] to A[4]. A becomes {{}, {1, 1}, {1}, {2, 3}, {2}, {}}. Number of unique elements in A[4] is 2.
  • For Third query {5, 1} move all elements from A[5] to A[1]. A becomes {{2}, {1, 1}, {1}, {2, 3}, {}, {}}. Number of unique elements in A[1] is 1.
  • For Fourth query {3, 6} move all elements from A[3] to A[6]. A becomes {{2}, {1, 1}, {}, {2, 3}, {}, {1}}. Number of unique elements in A[6] is 1.
  • For Fifth query {4, 6} move all elements from A{4] to A[6]. A becomes {{2}, {1, 1}, {}, {}, {}, {1, 2, 3}}. Number of unique elements in A[6] is 3.

Input: A[][1] = {{2}, {4}, {2}, {4}, {2}}, Q[][2] = {{3, 1}, {2, 5}, {3, 2}}
Output: 1 2 0
Explanation:

  • For First query {3, 1} move all elements from A[3] to A[1]. A becomes {{2, 2}, {4}, {}, {4}, {2}}. Number of unique elements in A[1] is 1.
  • For Second query {2, 5} move all elements from A[2] to A[5]. A becomes {{2, 2}, {}, {}, {4}, {2, 4}}. Number of unique elements in A[5] is 2.
  • For Third query {3, 2} move all elements from A[3] to A[2]. A becomes {{2, 2}, {}, {}, {4}, {2, 4}}. Number of unique elements in A[2] is 0.

Efficient Approach: To solve the problem follow the below idea.

This problem is an application of the “union-by-size / small-to-large heuristic”. This algorithm depends upon fact that swapping index of sets take place in constant time, and merging a smaller set of size M into a larger set of size N takes O(MlogN). When merging sets, always move from a smaller set to a larger set. So whenever we need to move some elements from larger to smaller set we just move smaller size set elements to larger size set elements and swap their indexes.

Below are the steps for the above approach:

  • Declaring vector of sets V[N].
  • Create an HashMap for dealing with the indexes.
  • Insert all N arrays from A[][1] to N sets and initialize index map ind.
  • Iterate for M queries and for each query
  • Declare two variables x(which stores set which is to be moved) and y(which will take all incoming elements from other set).
  • whenever we find elements in the set [x] is less than set[y] we insert elements in y set and if it is greater than set[y] then we insert all element in set [x] and swap their indexes.
  • At the end of each query print the size of set V[ind[y]].

Below is the implementation of the above approach:

C++
// C++ code to implement the approach #include <bits/stdc++.h> using namespace std;  // Function to Queries to find // number of unique elements in array void queriesTofindUnique(int a[][1], int n, int Q[][2],                          int m) {     // Creating a vector of sets     vector<set<int> > v(n);      // Creating Map to find out which index pointing towards     // which index     unordered_map<int, int> ind;      for (int i = 0; i < n; i++) {          // Insert each value in the set of perticular index         v[i].insert(a[i][0]);          // Currently each index is pointing towards itself         ind[i] = i;     }     for (int i = 0; i < m; i++) {          int x = Q[i][0];         int y = Q[i][1];         // Making index Zero Based         --x;         --y;         if (v[ind[x]].size() <= v[ind[y]].size()) {             // Transfer all elements from x to y index             for (auto el : v[ind[x]])                 v[ind[y]].insert(el);             // Clearing all values from 'x' index             v[ind[x]].clear();         }         else {             // Transfer all elements from y to x index             for (auto el : v[ind[y]])                 v[ind[x]].insert(el);             // Clearing all values from 'y' index             v[ind[y]].clear();             // Now index x will point towards y and y             // towards x             swap(ind[x], ind[y]);         }         // printing the size of Q[i][1]         cout << v[ind[y]].size() << " ";     }     cout << "\n"; }  // Driver Code int32_t main() {      // Input 1     int N = 6, M = 5;     int A[][1]         = { { 1 }, { 1 }, { 1 }, { 2 }, { 2 }, { 3 } };     int Q[][2] = {         { 1, 2 }, { 6, 4 }, { 5, 1 }, { 3, 6 }, { 4, 6 }     };      // Function Call     queriesTofindUnique(A, N, Q, M);      return 0; } 
Java
/*code by Flutterfly */ import java.util.*;  public class Main {      // Function to Queries to find     // number of unique elements in array     static void queriesToFindUnique(int[][] a, int n, int[][] Q, int m) {         // Creating a vector of sets         ArrayList<HashSet<Integer>> v = new ArrayList<>(n);          // Creating Map to find out which index pointing towards         // which index         HashMap<Integer, Integer> ind = new HashMap<>();          for (int i = 0; i < n; i++) {             // Insert each value in the set of particular index             HashSet<Integer> set = new HashSet<>();             set.add(a[i][0]);             v.add(set);              // Currently each index is pointing towards itself             ind.put(i, i);         }          for (int i = 0; i < m; i++) {             int x = Q[i][0];             int y = Q[i][1];              // Making index Zero Based             --x;             --y;              if (v.get(ind.get(x)).size() <= v.get(ind.get(y)).size()) {                 // Transfer all elements from x to y index                 for (int el : v.get(ind.get(x))) {                     v.get(ind.get(y)).add(el);                 }                 // Clearing all values from 'x' index                 v.get(ind.get(x)).clear();             } else {                 // Transfer all elements from y to x index                 for (int el : v.get(ind.get(y))) {                     v.get(ind.get(x)).add(el);                 }                 // Clearing all values from 'y' index                 v.get(ind.get(y)).clear();                 // Now index x will point towards y and y                 // towards x                 Collections.swap(v, ind.get(x), ind.get(y));             }             // printing the size of Q[i][1]             System.out.print(v.get(ind.get(y)).size() + " ");         }         System.out.println();     }      // Driver Code     public static void main(String[] args) {         // Input 1         int N = 6, M = 5;         int[][] A = {{1}, {1}, {1}, {2}, {2}, {3}};         int[][] Q = {             {1, 2}, {6, 4}, {5, 1}, {3, 6}, {4, 6}         };          // Function Call         queriesToFindUnique(A, N, Q, M);     } } 
Python3
def queries_to_find_unique(a, n, q, m):     """     Function to Queries to find number of unique elements in array     """     # Creating a list of sets     v = [set([a[i][0]]) for i in range(n)]      # Creating Map to find out which index pointing towards     # which index     ind = {i: i for i in range(n)}      for i in range(m):         x, y = q[i][0], q[i][1]         # Making index Zero Based         x -= 1         y -= 1          if len(v[ind[x]]) <= len(v[ind[y]]):             # Transfer all elements from x to y index             v[ind[y]].update(v[ind[x]])             # Clearing all values from 'x' index             v[ind[x]].clear()         else:             # Transfer all elements from y to x index             v[ind[x]].update(v[ind[y]])             # Clearing all values from 'y' index             v[ind[y]].clear()             # Now index x will point towards y and y towards x             ind[x], ind[y] = ind[y], ind[x]          # Printing the size of Q[i][1]         print(len(v[ind[y]]), end=" ")      print("\n")   # Driver Code if __name__ == "__main__":     # Input 1     N, M = 6, 5     A = [[1], [1], [1], [2], [2], [3]]     Q = [[1, 2], [6, 4], [5, 1], [3, 6], [4, 6]]      # Function Call     queries_to_find_unique(A, N, Q, M) 
C#
//code by Flutterfly  using System; using System.Collections.Generic;  public class MainClass {     // Function to Queries to find     // number of unique elements in array     static void QueriesToFindUnique(int[][] a, int n, int[][] Q, int m)     {         // Creating a List of Sets         List<HashSet<int>> v = new List<HashSet<int>>(n);          // Creating Dictionary to find out which index pointing towards         // which index         Dictionary<int, int> ind = new Dictionary<int, int>();          for (int i = 0; i < n; i++)         {             // Insert each value in the set of particular index             HashSet<int> set = new HashSet<int>();             set.Add(a[i][0]);             v.Add(set);              // Currently each index is pointing towards itself             ind[i] = i;         }          for (int i = 0; i < m; i++)         {             int x = Q[i][0];             int y = Q[i][1];              // Making index Zero Based             --x;             --y;              if (v[ind[x]].Count <= v[ind[y]].Count)             {                 // Transfer all elements from x to y index                 foreach (int el in v[ind[x]])                 {                     v[ind[y]].Add(el);                 }                 // Clearing all values from 'x' index                 v[ind[x]].Clear();             }             else             {                 // Transfer all elements from y to x index                 foreach (int el in v[ind[y]])                 {                     v[ind[x]].Add(el);                 }                 // Clearing all values from 'y' index                 v[ind[y]].Clear();                 // Now index x will point towards y and y                 // towards x                 int temp = ind[x];                 ind[x] = ind[y];                 ind[y] = temp;             }             // printing the size of Q[i][1]             Console.Write(v[ind[y]].Count + " ");         }         Console.WriteLine();     }      // Driver Code     public static void Main(string[] args)     {         // Input 1         int N = 6, M = 5;         int[][] A = { new[] { 1 }, new[] { 1 }, new[] { 1 }, new[] { 2 }, new[] { 2 }, new[] { 3 } };         int[][] Q = {             new[] { 1, 2 }, new[] { 6, 4 }, new[] { 5, 1 }, new[] { 3, 6 }, new[] { 4, 6 }         };          // Function Call         QueriesToFindUnique(A, N, Q, M);     } } 
JavaScript
//code by Flutterfly  // Function to Queries to find // number of unique elements in array function queriesToFindUnique(a, n, Q, m) {     // Creating an array of sets     let v = new Array(n).fill(null).map(() => new Set());      // Creating Map to find out which index pointing towards     // which index     let ind = new Map();      for (let i = 0; i < n; i++) {         // Insert each value in the set of particular index         v[i].add(a[i][0]);          // Currently each index is pointing towards itself         ind.set(i, i);     }      for (let i = 0; i < m; i++) {         let x = Q[i][0];         let y = Q[i][1];          // Making index Zero Based         --x;         --y;          if (v[ind.get(x)].size <= v[ind.get(y)].size) {             // Transfer all elements from x to y index             for (let el of v[ind.get(x)]) {                 v[ind.get(y)].add(el);             }             // Clearing all values from 'x' index             v[ind.get(x)].clear();         } else {             // Transfer all elements from y to x index             for (let el of v[ind.get(y)]) {                 v[ind.get(x)].add(el);             }             // Clearing all values from 'y' index             v[ind.get(y)].clear();             // Now index x will point towards y and y             // towards x             let temp = ind.get(x);             ind.set(x, ind.get(y));             ind.set(y, temp);         }         // printing the size of Q[i][1]         process.stdout.write(v[ind.get(y)].size + " ");     }     console.log(); }  // Driver Code // Input 1 let N = 6, M = 5; let A = [[1], [1], [1], [2], [2], [3]]; let Q = [     [1, 2], [6, 4], [5, 1], [3, 6], [4, 6] ];  // Function Call queriesToFindUnique(A, N, Q, M); 

Output
1 2 1 1 3 

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


Next Article
Divide the array into minimum number of sub-arrays having unique elements
author
iamkiran2233
Improve
Article Tags :
  • Graph
  • Geeks Premier League
  • DSA
  • Data Structures-Hash
  • disjoint-set
  • Geeks Premier League 2023
Practice Tags :
  • Graph

Similar Reads

  • Divide the array into minimum number of sub-arrays having unique elements
    Given an array arr. The task is to divide the array into the minimum number of subarrays containing unique elements and return the count of such subarrays. Note: An array element cannot be present in more than one subarray.Examples : Input : arr[] = {1, 2, 1, 1, 2, 3}Output : 3Explanation : The suba
    8 min read
  • Count of Unique elements after inserting average of MEX and Array Max K times
    Given an array A[] of N non-negative integers and an integer K. Each time, you can do the following two operations Find Average of MAX and MEX(rounded up to closest greater integer) of the array.Insert calculated average in the array. After performing the above operation K times, find the count of u
    9 min read
  • Find sum of all unique elements in the array for K queries
    Given an arrays arr[] in which initially all elements are 0 and another array Q[][] containing K queries where every query represents a range [L, R], the task is to add 1 to each subarrays where each subarray is defined by the range [L, R], and return sum of all unique elements.Note: One-based index
    8 min read
  • LCM of unique elements present in an array
    Given an array arr[] consisting of N positive integers, the task is to find the LCM of all unique elements of the given array. If the array does not contain any unique elements, then print "-1". Examples: Input: arr[] = {1, 2, 1, 3, 3, 4}Output: 4Explanation: The unique elements of the given array a
    8 min read
  • Number of unique pairs in an array
    Given an array of N elements, the task is to find all the unique pairs that can be formed using the elements of a given array. Examples: Input: arr[] = {1, 1, 2} Output: 4 (1, 1), (1, 2), (2, 1), (2, 2) are the only possible pairs. Input: arr[] = {1, 2, 3} Output: 9 Naive approach: The simple soluti
    6 min read
  • Print all unique elements present in a sorted array
    Given a sorted array arr[] of size N, the task is to print all the unique elements in the array. An array element is said to be unique if the frequency of that element in the array is 1. Examples: Input: arr[ ] = {1, 1, 2, 2, 3, 4, 5, 5}Output: 3 4Explanation: Since 1, 2, 5 are occurring more than o
    5 min read
  • Minimize sum of count of unique elements in Array after dividing into [1, N] subsets
    Given an array arr[] of length N, the task is to find the minimum number of unique elements possible in total when the array is divided into K subsets (for all K in the range [1, N]) i.e. sum of count of unique elements present in each subset after dividing the given array into K subsets. Examples:
    7 min read
  • Queries for number of distinct elements from a given index till last index in an array
    Given a array ‘a[]’ of size n and number of queries q. Each query can be represented by a integer m. Your task is to print the number of distinct integers from index m to n i.e till last element of the array. Examples: Input: arr[] = {1, 2, 3, 1, 2, 3, 4, 5}, q[] = {1, 4, 6, 8} Output: 5 5 3 1 In qu
    6 min read
  • Find sum of non-repeating (distinct) elements in an array
    Given an integer array with repeated elements, the task is to find the sum of all distinct elements in the array.Examples: Input : arr[] = {12, 10, 9, 45, 2, 10, 10, 45,10};Output : 78Here we take 12, 10, 9, 45, 2 for sumbecause it's distinct elements Input : arr[] = {1, 10, 9, 4, 2, 10, 10, 45 , 4}
    14 min read
  • Minimum number of distinct elements present in a K-length subsequence in an array
    Given an array A[] consisting of N integers and an integer K, the task is to count the minimum number of distinct elements present in a subsequence of length K of the given array, A. Examples: Input: A = {3, 1, 3, 2, 3, 4, 5, 4}, K = 4Output: 2Explanation: The subsequence of length 4 containing mini
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences