Unlike a set, a multiset may contain multiple occurrences of same number. The multiset equivalence problem states to check if two given multisets are equal or not. For example let A = {1, 2, 3} and B = {1, 1, 2, 3}. Here A is set but B is not (1 occurs twice in B), whereas A and B are both multisets. More formally, “Are the sets of pairs defined as equal for the two given multisets?” Given two multisets A and B, write a program to check if the two multisets are equal. Note: Elements in the multisets can be of order 109 Examples:
Input : A = {1, 1, 3, 4},
B = {1, 1, 3, 4}
Output : Yes
Input : A = {1, 3},
B = {1, 1}
Output : No
Since the elements are as large as 10^9 we cannot use direct index table. One solution is to sort both multisets and compare them one by one.
Vector<Integer> a = newVector<Integer>(Arrays.asList( 7, 7, 5));
Vector<Integer> b = newVector<Integer>(Arrays.asList( 7, 5, 5));
if(areSame(a, b))
System.out.print("Yes\n");
else
System.out.print("No\n");
}
}
// This code is contributed by PrinciRaj1992
Python3
# Python3 program to check if
# two given multisets are equivalent
defareSame(a, b):
# sort the elements of both multisets
a.sort();
b.sort();
# Return true if both multisets are same.
return(a ==b);
# Driver Code
a =[ 7, 7, 5];
b =[ 7, 5, 5];
if(areSame(a, b)):
print("Yes");
else:
print("No");
# This code is contributed by Princi Singh
C#
// C# program to check if two given multisets
// are equivalent
usingSystem;
usingSystem.Collections.Generic;
classGFG
{
staticboolareSame(List<int>a, List<int>b)
{
// sort the elements of both multisets
a.Sort();
b.Sort();
// Return true if both multisets are same.
return(a == b);
}
// Driver code
publicstaticvoidMain()
{
List<int> a = newList<int> { 7, 7, 5 };
List<int> b = newList<int> { 7, 5, 5 };
if(areSame(a, b))
Console.WriteLine("Yes\n");
else
Console.WriteLine("No\n");
}
}
// This code is contributed by Rajput-Ji
Javascript
<script>
// JavaScript program to check if two given multisets
// are equivalent
functionareSame(a, b) {
// sort the elements of both multisets
a.sort((a, b) => a - b);
b.sort((a, b) => a - b);
// Return true if both multisets are same.
return(a == b);
}
let a = [7, 7, 5], b = [7, 5, 5];
if(areSame(a, b))
document.write("Yes<br>");
else
document.write("No<br>");
</script>
Output:
No
Time Complexity: O(n*log(n)) Auxiliary Space: O(1)
A better solution is to use hashing. We create two empty hash tables (implemented using unordered_map in C++). We first insert all items of first multimap in first table and all items of second multiset in second table. Now we check if both hash tables contain same items and frequencies or not.
C++
// C++ program to check if two given multisets
// are equivalent
#include <bits/stdc++.h>
usingnamespacestd;
boolareSame(vector<int>& a, vector<int>& b)
{
if(a.size() != b.size())
returnfalse;
// Create two unordered maps m1 and m2
// and insert values of both vectors.
unordered_map<int, int> m1, m2;
for(inti = 0; i < a.size(); i++) {
m1[a[i]]++;
m2[b[i]]++;
}
// Now we check if both unordered_maps
// are same of not.
for(autox : m1) {
if(m2.find(x.first) == m2.end() ||
m2[x.first] != x.second)
returnfalse;
}
returntrue;
}
// Driver code
intmain()
{
vector<int> a({ 7, 7, 5 }), b({ 7, 7, 5 });
if(areSame(a, b))
cout << "Yes\n";
else
cout << "No\n";
return0;
}
Java
// Java program to check if two given multisets
// are equivalent
importjava.util.*;
classGFG
{
staticbooleanareSame(int[]a, int[]b)
{
if(a.length != b.length)
returnfalse;
// Create two unordered maps m1 and m2
// and insert values of both vectors.
HashMap<Integer, Integer> m1, m2;
m1 = newHashMap<Integer, Integer>();
m2 = newHashMap<Integer, Integer>();
for(inti = 0; i < a.length; i++)
{
if(m1.containsKey(a[i]))
{
m1.put(a[i], m1.get(a[i]) + 1);
}
else
{
m1.put(a[i], 1);
}
if(m2.containsKey(b[i]))
{
m2.put(b[i], m2.get(b[i]) + 1);
}
else
{
m2.put(b[i], 1);
}
}
// Now we check if both unordered_maps
// are same of not.
for(Map.Entry<Integer, Integer> x : m1.entrySet())
{
if(!m2.containsKey(x.getKey()) ||
m2.get(x.getKey()) != x.getValue())
returnfalse;
}
returntrue;
}
// Driver code
publicstaticvoidmain(String args[])
{
int[]a = { 7, 7, 5};
int[]b = { 7, 7, 5};
if(areSame(a, b))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by 29AjayKumar
Python3
# Python program to check if two given multisets
# are equivalent
defareSame(a, b):
if(len(a) !=len(b)):
returnFalse
# Create two unordered maps m1 and m2
# and insert values of both vectors.
m1 ={}
m2 ={}
fori inrange(len(a)):
if(a[i] inm1):
m1[a[i]] =m1[a[i]] +1
else:
m1[a[i]] =1
if(b[i] inm2):
m2[b[i]] =m2[b[i]] +1
else:
m2[b[i]] =1
# Now we check if both unordered_maps
# are same of not.
fork inm1.keys():
if(k notinm1 orm2[k] !=m1[k]):
returnFalse
returnTrue
# Driver code
a =[7, 7, 5]
b =[7, 7, 5]
if(areSame(a, b)):
print("Yes")
else:
print("No")
# This code is contributed by Saurabh Jaiswal
C#
// C# program to check if two given multisets
// are equivalent
usingSystem;
usingSystem.Collections.Generic;
classGFG
{
staticboolareSame(int[]a, int[]b)
{
if(a.Length != b.Length)
returnfalse;
// Create two unordered maps m1 and m2
// and insert values of both vectors.
Dictionary<int, int> m1, m2;
m1 = newDictionary<int, int>();
m2 = newDictionary<int, int>();
for(inti = 0; i < a.Length; i++)
{
if(m1.ContainsKey(a[i]))
{
m1[a[i]] = m1[a[i]] + 1;
}
else
{
m1.Add(a[i], 1);
}
if(m2.ContainsKey(b[i]))
{
m2[b[i]] = m2[b[i]] + 1;
}
else
{
m2.Add(b[i], 1);
}
}
// Now we check if both unordered_maps
// are same of not.
foreach(KeyValuePair<int, int> x inm1)
{
if(!m2.ContainsKey(x.Key) ||
m2[x.Key] != x.Value)
returnfalse;
}
returntrue;
}
// Driver code
publicstaticvoidMain(String []args)
{
int[]a = { 7, 7, 5 };
int[]b = { 7, 7, 5 };
if(areSame(a, b))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by 29AjayKumar
Javascript
<script>
// JavaScript program to check if two given multisets
Time complexity : O(n) under the assumption that unordered_map find() and insert() operations work in O(1) time. Auxiliary Space: 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!