Check if two unsorted arrays (with duplicates allowed) have same elements
Last Updated :
03 Apr, 2023
Given two unsorted arrays, check whether both arrays have the same set of elements or not.
Examples:
Input : A = {2, 5, 6, 8, 10, 2, 2}
B = {2, 5, 5, 6, 8, 5, 6}
Output : No
Input : A = {2, 5, 6, 8, 2, 10, 2}
B = {2, 5, 6, 8, 2, 10, 2}
Output : Yes
Input : A = {2, 5, 8, 6, 10, 2, 2}
B = {2, 5, 6, 8, 2, 10, 2}
Output : Yes
Method 1 (Simple):
A simple solution to this problem is to check if each element of A is present in B. But this approach will lead to a wrong answer in case of multiple instances of an element is present in B. To overcome this issue, we mark visited instances of B[] using an auxiliary array visited[].
C++
#include <bits/stdc++.h>
using namespace std;
bool areSameSet(vector< int > A, vector< int > B)
{
int n = A.size();
if (B.size() != n)
return false ;
vector< bool > visited(n, false );
for ( int i = 0; i < n; i++) {
int j = 0;
for (j = 0; j < n; j++)
{
if (A[i] == B[j] && visited[j] == false )
{
visited[j] = true ;
break ;
}
}
if (j == n)
return false ;
}
return true ;
}
int main()
{
vector< int > A, B;
A.push_back(2);
A.push_back(5);
A.push_back(10);
A.push_back(6);
A.push_back(8);
A.push_back(2);
A.push_back(2);
B.push_back(2);
B.push_back(5);
B.push_back(6);
B.push_back(8);
B.push_back(10);
B.push_back(2);
B.push_back(2);
areSameSet(A, B)? cout << "Yes" : cout << "No" ;
}
|
Java
import java.util.*;
class GFG
{
static boolean areSameSet(Vector<Integer> A, Vector<Integer> B)
{
int n = A.size();
if (B.size() != n)
{
return false ;
}
Vector<Boolean> visited = new Vector<Boolean>();
for ( int i = 0 ; i < n; i++)
{
visited.add(i, Boolean.FALSE);
}
for ( int i = 0 ; i < n; i++)
{
int j = 0 ;
for (j = 0 ; j < n; j++)
{
if (A.get(i) == B.get(j) && visited.get(j) == false )
{
visited.add(j, Boolean.TRUE);
break ;
}
}
if (j == n)
{
return false ;
}
}
return true ;
}
public static void main(String[] args)
{
Vector<Integer> A = new Vector<>();
Vector<Integer> B = new Vector<>();
A.add( 2 );
A.add( 5 );
A.add( 10 );
A.add( 6 );
A.add( 8 );
A.add( 2 );
A.add( 2 );
B.add( 2 );
B.add( 5 );
B.add( 6 );
B.add( 8 );
B.add( 10 );
B.add( 2 );
B.add( 2 );
if (areSameSet(A, B))
{
System.out.println( "Yes" );
}
else
{
System.out.println( "No" );
}
}
}
|
Python3
def areSameSet(A, B):
n = len (A)
if ( len (B) ! = n):
return False
visited = [ False for i in range (n)]
for i in range (n):
j = 0
for j in range (n):
if (A[i] = = B[j] and
visited[j] = = False ):
visited[j] = True
break
if (j = = n):
return False
return True
A = []
B = []
A.append( 2 )
A.append( 5 )
A.append( 10 )
A.append( 6 )
A.append( 8 )
A.append( 2 )
A.append( 2 )
B.append( 2 )
B.append( 5 )
B.append( 6 )
B.append( 8 )
B.append( 10 )
B.append( 2 )
B.append( 2 )
if (areSameSet(A, B)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static Boolean areSameSet(List< int > A, List< int > B)
{
int n = A.Count;
if (B.Count != n)
{
return false ;
}
List<Boolean> visited = new List<Boolean>();
for ( int i = 0; i < n; i++)
{
visited.Insert(i, false );
}
for ( int i = 0; i < n; i++)
{
int j = 0;
for (j = 0; j < n; j++)
{
if (A[i] == B[j] && visited[j] == false )
{
visited.Insert(j, true );
break ;
}
}
if (j == n)
{
return false ;
}
}
return true ;
}
public static void Main(String[] args)
{
List< int > A = new List< int >();
List< int > B = new List< int >();
A.Add(2);
A.Add(5);
A.Add(10);
A.Add(6);
A.Add(8);
A.Add(2);
A.Add(2);
B.Add(2);
B.Add(5);
B.Add(6);
B.Add(8);
B.Add(10);
B.Add(2);
B.Add(2);
if (areSameSet(A, B))
{
Console.WriteLine( "Yes" );
}
else
{
Console.WriteLine( "No" );
}
}
}
|
Javascript
<script>
function areSameSet(A,B)
{
let n = A.length;
if (B.length != n)
{
return false ;
}
let visited = [];
for (let i = 0; i < n; i++)
{
visited.push( false );
}
for (let i = 0; i < n; i++)
{
let j = 0;
for (j = 0; j < n; j++)
{
if (A[i] == B[j] && visited[j] == false )
{
visited[j]= true ;
break ;
}
}
if (j == n)
{
return false ;
}
}
return true ;
}
let A=[];
let B=[];
A.push(2);
A.push(5);
A.push(10);
A.push(6);
A.push(8);
A.push(2);
A.push(2);
B.push(2);
B.push(5);
B.push(6);
B.push(8);
B.push(10);
B.push(2);
B.push(2);
if (areSameSet(A, B))
{
document.write( "Yes" );
}
else
{
document.write( "No" );
}
</script>
|
Output:
Yes
Time complexity: O(n^2).
Method 2 (Sorting):
Sort both the arrays and compare corresponding elements of each array.
C++
#include <bits/stdc++.h>
using namespace std;
bool areSameSet(vector< int > A, vector< int > B)
{
int n = A.size();
if (B.size() != n)
return false ;
sort(A.begin(), A.end());
sort(B.begin(), B.end());
for ( int i = 0; i < n; i++)
if (A[i] != B[i])
return false ;
return true ;
}
int main()
{
vector< int > A, B;
A.push_back(2);
A.push_back(5);
A.push_back(10);
A.push_back(6);
A.push_back(8);
A.push_back(2);
A.push_back(2);
B.push_back(2);
B.push_back(5);
B.push_back(6);
B.push_back(8);
B.push_back(10);
B.push_back(2);
B.push_back(2);
areSameSet(A, B)? cout << "Yes" : cout << "No" ;
}
|
Java
import java.util.*;
class GFG
{
static boolean areSameSet(Vector<Integer> A,
Vector<Integer> B)
{
int n = A.size();
if (B.size() != n)
{
return false ;
}
Collections.sort(A);
Collections.sort(B);
for ( int i = 0 ; i < n; i++)
{
if (A.get(i) != B.get(i))
{
return false ;
}
}
return true ;
}
public static void main(String[] args)
{
Vector<Integer> A = new Vector<>();
Vector<Integer> B = new Vector<>();
A.add( 2 );
A.add( 5 );
A.add( 10 );
A.add( 6 );
A.add( 8 );
A.add( 2 );
A.add( 2 );
B.add( 2 );
B.add( 5 );
B.add( 6 );
B.add( 8 );
B.add( 10 );
B.add( 2 );
B.add( 2 );
if (areSameSet(A, B))
{
System.out.println( "Yes" );
}
else
{
System.out.println( "No" );
}
}
}
|
Python3
def areSameSet(A, B):
n = len (A)
if ( len (B) ! = n):
return False
A.sort()
B.sort()
for i in range (n):
if (A[i] ! = B[i]):
return False
return True
if __name__ = = "__main__" :
A = []
B = []
A.append( 2 )
A.append( 5 )
A.append( 10 )
A.append( 6 )
A.append( 8 )
A.append( 2 )
A.append( 2 )
B.append( 2 )
B.append( 5 )
B.append( 6 )
B.append( 8 )
B.append( 10 )
B.append( 2 )
B.append( 2 )
if areSameSet(A, B):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static Boolean areSameSet(List< int > A,
List< int > B)
{
int n = A.Count;
if (B.Count!= n)
{
return false ;
}
A.Sort();
B.Sort();
for ( int i = 0; i < n; i++)
{
if (A[i] != B[i])
{
return false ;
}
}
return true ;
}
public static void Main(String[] args)
{
List< int > A = new List< int >();
List< int > B = new List< int >();
A.Add(2);
A.Add(5);
A.Add(10);
A.Add(6);
A.Add(8);
A.Add(2);
A.Add(2);
B.Add(2);
B.Add(5);
B.Add(6);
B.Add(8);
B.Add(10);
B.Add(2);
B.Add(2);
if (areSameSet(A, B))
{
Console.WriteLine( "Yes" );
}
else
{
Console.WriteLine( "No" );
}
}
}
|
Javascript
<script>
function areSameSet(A, B)
{
let n = A.length;
if (B.length != n)
{
return false ;
}
A.sort( function (a, b){ return a - b;});
B.sort( function (a, b){ return a - b;});
for (let i = 0; i < n; i++)
{
if (A[i] != B[i])
{
return false ;
}
}
return true ;
}
let A = [];
let B = [];
A.push(2);
A.push(5);
A.push(10);
A.push(6);
A.push(8);
A.push(2);
A.push(2);
B.push(2);
B.push(5);
B.push(6);
B.push(8);
B.push(10);
B.push(2);
B.push(2);
if (areSameSet(A, B))
{
document.write( "Yes" );
}
else
{
document.write( "No" );
}
</script>
|
Output:
Yes
Time Complexity: O(n*log(n)).
Method 3 (Hashing):
We can decrease the time complexity of the above problem by using a Hash table. First, we iterate through A and mark the number of instances of each element of A in a Hash Table. Then we iterate through B and decrease the corresponding value in the hash table. If in the end if all the entries of the hash table are zero, the answer will be “Yes” else “No”.
C++
#include <bits/stdc++.h>
using namespace std;
bool areSameSet(vector< int > A, vector< int > B){
int n = A.size();
if (B.size() != n)
return false ;
unordered_map< int , int > m;
for ( int i = 0; i < n; i++)
m[A[i]]++;
for ( int i = 0; i < n; i++)
m[B[i]]--;
for ( auto i : m){
if (i.second != 0){
return false ;
}
}
return true ;
}
int main(){
vector< int > A = {2, 5, 10, 6, 8, 2, 2};
vector< int > B = {2, 5, 6, 8, 10, 2, 2};
areSameSet(A, B)? cout << "Yes" : cout << "No" ;
}
|
Java
import java.util.HashMap;
class GFG
{
static boolean areSameSet( int [] A, int [] B)
{
int n = A.length;
if (B.length != n)
return false ;
HashMap<Integer,
Integer> m = new HashMap<>();
for ( int i = 0 ; i < n; i++)
m.put(A[i], m.get(A[i]) == null ? 1 :
m.get(A[i]) + 1 );
for ( int i = 0 ; i < n; i++)
m.put(B[i], m.get(B[i]) - 1 );
for (HashMap.Entry<Integer,
Integer> entry : m.entrySet())
if (entry.getValue() != 0 )
return false ;
return true ;
}
public static void main(String[] args)
{
int [] A = { 2 , 5 , 10 , 6 , 8 , 2 , 2 };
int [] B = { 2 , 5 , 6 , 8 , 10 , 2 , 2 };
if (areSameSet(A, B))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def areSameSet(A, B):
n = len (A)
if ( len (B) ! = n):
return False
m = {}
for i in range (n):
if A[i] not in m:
m[A[i]] = 1
else :
m[A[i]] + = 1
for i in range (n):
if B[i] in m:
m[B[i]] - = 1
for i in m:
if (m[i] ! = 0 ):
return False
return True
A = []
B = []
A.append( 2 )
A.append( 5 )
A.append( 10 )
A.append( 6 )
A.append( 8 )
A.append( 2 )
A.append( 2 )
B.append( 2 )
B.append( 5 )
B.append( 6 )
B.append( 8 )
B.append( 10 )
B.append( 2 )
B.append( 2 )
if (areSameSet(A, B)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static bool areSameSet( int [] A, int [] B)
{
int n = A.Length;
if (B.Length != n)
return false ;
Dictionary< int , int > m = new Dictionary< int , int >();
for ( int i = 0; i < n; i++)
if (m.ContainsKey(A[i]))
m[A[i]] = m[A[i]] + 1;
else
m.Add(A[i], 1);
for ( int i = 0; i < n; i++)
if (m.ContainsKey(B[i]))
m[B[i]] = m[B[i]] - 1;
foreach (KeyValuePair< int , int > entry in m)
if (entry.Value != 0)
return false ;
return true ;
}
public static void Main(String[] args)
{
int [] A = { 2, 5, 10, 6, 8, 2, 2 };
int [] B = { 2, 5, 6, 8, 10, 2, 2 };
if (areSameSet(A, B))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
function areSameSet(A,B)
{
let n = A.length;
if (B.length != n)
return false ;
let m = new Map();
for (let i = 0; i < n; i++)
m.set(A[i], m.get(A[i]) == null ? 1 :
m.get(A[i]) + 1);
for (let i = 0; i < n; i++)
m.set(B[i], m.get(B[i]) - 1);
for (let [key, value] of m.entries())
if (value != 0)
return false ;
return true ;
}
let A=[2, 5, 10, 6, 8, 2, 2 ];
let B=[2, 5, 6, 8, 10, 2, 2];
if (areSameSet(A, B))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Output:
Yes
Time Complexity: O(n), where n is the number of elements in the given vector.
Auxiliary Space: O(n)
Similar Reads
Check if all duplicate elements in the Array are adjacent or not
Given an array arr[]. The task is to check whether duplicate elements in arr[] are contiguous or not. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6} Output: Yes Explanation: There is no duplicate element in arr[] so there is no need to check anything and answer is Yes. Input: arr[] = {1, 2, 2, 4} Outpu
4 min read
Last duplicate element in a sorted array
We have a sorted array with duplicate elements and we have to find the index of last duplicate element and print index of it and also print the duplicate element. If no such element found print a message. Examples: Input : arr[] = {1, 5, 5, 6, 6, 7} Output : Last index: 4 Last duplicate item: 6 Inpu
6 min read
Find Equal (or Middle) Point in a sorted array with duplicates
Given a sorted array of n size, the task is to find whether an element exists in the array from where the number of smaller elements is equal to the number of greater elements.If Equal Point appears multiple times in input array, return the index of its first occurrence. If doesn't exist, return -1.
9 min read
Find all pairs with a given sum in two unsorted arrays
Given two unsorted arrays of distinct elements, the task is to find all pairs from both arrays whose sum is equal to a given value X. Examples: Input: arr1[] = {-1, -2, 4, -6, 5, 7}, arr2[] = {6, 3, 4, 0} , x = 8Output: 4 4 5 3 Input: arr1[] = {1, 2, 4, 5, 7}, arr2[] = {5, 6, 3, 4, 8}, x = 9Output:
13 min read
Union of Two Sorted Arrays with Distinct Elements
Given two sorted arrays a[] and b[] with distinct elements, the task is to return union of both the arrays in sorted order. Note: Union of two arrays is an array having all distinct elements that are present in either array. Examples: Input: a[] = {1, 2, 3}, b[] = {2, 5, 7}Output: {1, 2, 3, 5, 7}Exp
15+ min read
Union of Two Arrays with Distinct Elements
Given two arrays a[] and b[] with distinct elements, the task is to return union of both the arrays in any order. Note: Union of two arrays is an array having all distinct elements that are present in either array. Examples: Input: a[] = {1, 2, 3}, b[] = {5, 2, 7}Output: {1, 2, 3, 5, 7}Explanation:
7 min read
Construct Binary Array having same number of unequal elements with two other Arrays
Given two binary arrays A[] and B[] of size N, the task is to construct the lexicographically smallest binary array X[] such that the number of non-equal elements in A and X is equal to the number of non-equal elements in B and X. If such an array does not exist return -1. Note: If there are multipl
12 min read
Find duplicates in constant array with elements 0 to N-1 in O(1) space
Given a constant array of n elements which contains elements from 1 to n-1, with any of these numbers appearing any number of times. Find any one of these repeating numbers in O(n) and using only constant memory space. Examples: Input : arr[] = {1, 2, 3, 4, 5, 6, 3} Output : 3 As the given array is
12 min read
Check if array contains contiguous integers with duplicates allowed
Given an array Arr of N integers(duplicates allowed). Print âYesâ if it is a set of contiguous integers else print âNoâ.Examples: Input: Arr = { 5, 2, 3, 6, 4, 4, 6, 6 } Output: Yes The elements of array form a contiguous set of integers which is {2, 3, 4, 5, 6} so the output is Yes.Input: Arr = { 1
13 min read
Check if an array contains all elements of a given range
An array containing positive elements is given. 'A' and 'B' are two numbers defining a range. Write a function to check if the array contains all elements in the given range. Examples : Input : arr[] = {1 4 5 2 7 8 3} A : 2, B : 5Output : YesInput : arr[] = {1 4 5 2 7 8 3} A : 2, B : 6Output : NoRec
15+ min read