Search code examples
c++arraysalgorithmequalityunordered-map

Check if two arrays are equal or not


I am trying to know if the two given arrays are equal or not, irrespective of permutation of elements but contains the same elements and frequency of all the elements must be same.

    int SameArray(int arr1[], int arr2[], int N, int M)
    {
        unordered_map<int, int> ump;
        if(N == M)
        {
            for(int i = 0; i < N; i++)
            {
                ump[arr1[i]]++;
            }
            for(int i = 0; i< M; i++)
            {
                if(ump.find(arr2[i]) != ump.end())
                    ump[arr2[i]]--;
            }
            if(ump.empty())
            return 1;
        }
        return 0;
    }

it's not showing any errors but output is always 0.


Solution

  • You're looking for std::is_permutation:

    bool SameArray(const std::vector<int>& arr1, const std::vector<int>& arr2) {
        return std::is_permutation(arr1.begin(), arr1.end(), arr2.begin(), arr2.end());
    }
    

    I took the liberty of changing your function return to bool and taking std::vectors as function parameters since this is C++ and not C.

    If you're curious about how std::permutation's comparasion works, look at its example implementation.