Check if two arrays are equal or not

we are given two arrays the task is to find if the two arrays are equal or not. Two arrays are  equal if they have same set of elements.

Example 1:

Input:
N = 5
A[] = {1,2,5,4,0}
B[] = {2,4,5,0,1}
Output: 1
Explanation: Both the array can be 
rearranged to {0,1,2,4,5}

Example 2:

Input:
N = 3
A[] = {1,2,5}
B[] = {2,4,15}
Output: 0
Explanation: A[] and B[] have only 
one common value.


method 1:

1)sort both the vectors

2)traverse through vector and compare the elements if any of the elements dont matchh than return 0

3)else return 1

c++ implementation:

bool check(vector<ll> a, vector<ll> b, int n)
    {
        sort(a.begin(),a.end());
        sort(b.begin(),b.end());
        
        int x=0;
        for(int i=0;i<n;i++)
        {
            if(a[i]!=b[x])
            return 0;
            x++;
        }
        
        return 1;
    }
Time Complexity: O(nlogn) 
space Complexity: O(1) 



method 2:
  • Use a map or HashMap to store the frequency of elements.
  • Increment frequencies of elements present in first array.
  • Decrement frequencies of elements present in second array.
  • Iterate over the map.
  • If frequency of any element now is not zero it means that its count in two arrays was not equal.
  • Return true or false.

c++ implementation:

    bool check(vector<ll> a, vector<ll> b, int N) 
  { 
      unordered_map<ll,ll>m;
      vector<int>::iterator i;
for(auto i=a.begin();i!=a.end();i++) { m[*i]++; } for(auto i=b.begin();i!=b.end();i++) { m[*i]--; } for(auto it=m.begin();it!=m.end();it++) { if(it->second!=0) return 0; } return 1; }
Time Complexity: O(n) 
space Complexity: O(n) 

No comments

darkmode