Open In App

Check if two arrays are equal or not

Last Updated : 20 Jun, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given two arrays, arr1 and arr2 of equal length N, the task is to determine if the given arrays are equal or not. Two arrays are considered equal if:

  • Both arrays contain the same set of elements.
  • The arrangements (or permutations) of elements may be different.
  • If there are repeated elements, the counts of each element must be the same in both arrays.

Examples: 

Input: arr1[] = {1, 2, 5, 4, 0}, arr2[] = {2, 4, 5, 0, 1}
Output: Yes

Input: arr1[] = {1, 2, 5, 4, 0, 2, 1}, arr2[] = {2, 4, 5, 0, 1, 1, 2} 
Output: Yes

 Input: arr1[] = {1, 7, 1}, arr2[] = {7, 7, 1}
Output: No

Approaches to check if two arrays are equal or not

[Naive Approach] Using Sorting – O(N*log(N)) time and O(1) auxiliary Space

The basic idea is to sort the both given arrays and idea behind sorting is that once both arrays are sorted, they will be identical if and only if they contain the same elements in the same quantities. After sorting, we compare the arrays element by element. If any pair of corresponding elements in the sorted arrays differ, we return false (i.e indicating the arrays are not equal). If all elements match, we return true.

Code Implementation:

C++
// C++ program to find given two array
// are equal or not
#include <bits/stdc++.h>
using namespace std;

// Returns true if arr1[0..n-1] and arr2[0..m-1]
// contain same elements.
bool areEqual(int arr1[], int arr2[], int N, int M)
{
    // If lengths of array are not equal means
    // array are not equal
    if (N != M)
        return false;

    // Sort both arrays
    sort(arr1, arr1 + N);
    sort(arr2, arr2 + M);

    // Linearly compare elements
    for (int i = 0; i < N; i++)
        if (arr1[i] != arr2[i])
            return false;

    // If all elements were same.
    return true;
}

// Driver's Code
int main()
{
    int arr1[] = { 3, 5, 2, 5, 2 };
    int arr2[] = { 2, 3, 5, 5, 2 };
    int N = sizeof(arr1) / sizeof(int);
    int M = sizeof(arr2) / sizeof(int);

    // Function call
    if (areEqual(arr1, arr2, N, M))
        cout << "Yes";
    else
        cout << "No";
    return 0;
}
Java
// Java program to find given two array
// are equal or not
import java.io.*;
import java.util.*;

class GFG {
    // Returns true if arr1[0..n-1] and
    // arr2[0..m-1] contain same elements.
    public static boolean areEqual(int arr1[], int arr2[])
    {
        int N = arr1.length;
        int M = arr2.length;

        // If lengths of array are not equal means
        // array are not equal
        if (N != M)
            return false;

        // Sort both arrays
        Arrays.sort(arr1);
        Arrays.sort(arr2);

        // Linearly compare elements
        for (int i = 0; i < N; i++)
            if (arr1[i] != arr2[i])
                return false;

        // If all elements were same.
        return true;
    }

    // Driver code
    public static void main(String[] args)
    {
        int arr1[] = { 3, 5, 2, 5, 2 };
        int arr2[] = { 2, 3, 5, 5, 2 };

        // Function call
        if (areEqual(arr1, arr2))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
Python
# Python3 program to find given
# two array are equal or not

# Returns true if arr1[0..n-1] and
# arr2[0..m-1] contain same elements.


def areEqual(arr1, arr2, N, M):

    # If lengths of array are not
    # equal means array are not equal
    if (N != M):
        return False

    # Sort both arrays
    arr1.sort()
    arr2.sort()

    # Linearly compare elements
    for i in range(0, N):
        if (arr1[i] != arr2[i]):
            return False

    # If all elements were same.
    return True


# Driver Code
if __name__ == "__main__":
    arr1 = [3, 5, 2, 5, 2]
    arr2 = [2, 3, 5, 5, 2]
    n = len(arr1)
    m = len(arr2)

    if (areEqual(arr1, arr2, n, m)):
        print("Yes")
    else:
        print("No")
C#
// C# program for the above approach
using System;

class GFG {

    // Returns true if arr1[0..n-1] and
    // arr2[0..m-1] contain same elements.
    public static bool areEqual(int[] arr1, int[] arr2)
    {
        int N = arr1.Length;
        int M = arr2.Length;

        // If lengths of array are not
        // equal means array are not equal
        if (N != M)
            return false;

        // Sort both arrays
        Array.Sort(arr1);
        Array.Sort(arr2);

        // Linearly compare elements
        for (int i = 0; i < N; i++)
            if (arr1[i] != arr2[i])
                return false;

        // If all elements were same.
        return true;
    }

    // Driver's code
    public static void Main()
    {
        int[] arr1 = { 3, 5, 2, 5, 2 };
        int[] arr2 = { 2, 3, 5, 5, 2 };

        // Function call
        if (areEqual(arr1, arr2))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}

// This code is contributed by anuj_67.
Javascript
<script>

// JavaScript program for the above approach

    // Returns true if arr1[0..n-1] and arr2[0..m-1]
    // contain same elements.
    function areEqual(arr1, arr2)
    {
        let N = arr1.length;
        let M = arr2.length;

        // If lengths of array are not equal means
        // array are not equal
        if (N != M)
            return false;

        // Sort both arrays
        arr1.sort();
        arr2.sort();

        // Linearly compare elements
        for (let i = 0; i < N; i++)
            if (arr1[i] != arr2[i])
                return false;

        // If all elements were same.
        return true;
    }

// Driver Code
    let arr1 = [3, 5, 2, 5, 2];
    let arr2 = [2, 3, 5, 5, 2];

    if (areEqual(arr1, arr2))
        document.write("Yes");
    else
        document.write("No");

</script>
PHP
<?php
// PHP program to find given 
// two array are equal or not

// Returns true if arr1[0..n-1]
// and arr2[0..m-1] contain same elements.
function areEqual( $arr1, $arr2, $N, $M)
{
    // If lengths of array 
    // are not equal means
    // array are not equal
    if ($N != $M)
        return false;

    // Sort both arrays
    sort($arr1);
    sort($arr2);

    // Linearly compare elements
    for ( $i = 0; $i < $N; $i++)
        if ($arr1[$i] != $arr2[$i])
            return false;

    // If all elements were same.
    return true;
}

// Driver Code
$arr1 = array(3, 5, 2, 5, 2);
$arr2 = array(2, 3, 5, 5, 2);
$N = count($arr1);
$M = count($arr2);

// Function call
if (areEqual($arr1, $arr2, $N, $M))
    echo "Yes";
else
    echo "No";

?>

Output
Yes

Time Complexity: O(N*log(N)) 
Auxiliary Space: O(1)

[Expected Approach] Using Hashing – O(N) time and O(N) auxiliary space

The hashing approach is more efficient approach for this problem. The use of a hash map (or dictionary) is to count the occurrences of each element in one array and then verifying these counts against the second array.

Code Implementation:

C++
// C++ program for the above approach

#include <bits/stdc++.h>
using namespace std;

// Returns true if arr1[0..N-1] and arr2[0..M-1]
// contain same elements.
bool areEqual(int arr1[], int arr2[], int N, int M)
{
    // If lengths of arrays are not equal
    if (N != M)
        return false;

    // Store arr1[] elements and their counts in
    // hash map
    unordered_map<int, int> mp;
    for (int i = 0; i < N; i++)
        mp[arr1[i]]++;

    // Traverse arr2[] elements and check if all
    // elements of arr2[] are present same number
    // of times or not.
    for (int i = 0; i < N; i++) {
        // If there is an element in arr2[], but
        // not in arr1[]
        if (mp.find(arr2[i]) == mp.end())
            return false;

        // If an element of arr2[] appears more
        // times than it appears in arr1[]
        if (mp[arr2[i]] == 0)
            return false;
        // decrease the count of arr2 elements in the
        // unordered map
        mp[arr2[i]]--;
    }

    return true;
}

// Driver's Code
int main()
{
    int arr1[] = { 3, 5, 2, 5, 2 };
    int arr2[] = { 2, 3, 5, 5, 2 };
    int N = sizeof(arr1) / sizeof(int);
    int M = sizeof(arr2) / sizeof(int);

    // Function call
    if (areEqual(arr1, arr2, N, M))
        cout << "Yes";
    else
        cout << "No";
    return 0;
}
Java
// Java program for the above approach
import java.io.*;
import java.util.*;

class GFG {

    // Returns true if arr1[0..N-1] and arr2[0..M-1]
    // contain same elements.
    public static boolean areEqual(int arr1[], int arr2[])
    {
        int N = arr1.length;
        int M = arr2.length;

        // If lengths of arrays are not equal
        if (N != M)
            return false;

        // Store arr1[] elements and their counts in
        // hash map
        Map<Integer, Integer> map
            = new HashMap<Integer, Integer>();
        int count = 0;
        for (int i = 0; i < N; i++) {
            if (map.get(arr1[i]) == null)
                map.put(arr1[i], 1);
            else {
                count = map.get(arr1[i]);
                count++;
                map.put(arr1[i], count);
            }
        }

        // Traverse arr2[] elements and check if all
        // elements of arr2[] are present same number
        // of times or not.
        for (int i = 0; i < N; i++) {

            // If there is an element in arr2[], but
            // not in arr1[]
            if (!map.containsKey(arr2[i]))
                return false;

            // If an element of arr2[] appears more
            // times than it appears in arr1[]
            if (map.get(arr2[i]) == 0)
                return false;

            count = map.get(arr2[i]);
            --count;
            map.put(arr2[i], count);
        }

        return true;
    }

    // Driver's code
    public static void main(String[] args)
    {
        int arr1[] = { 3, 5, 2, 5, 2 };
        int arr2[] = { 2, 3, 5, 5, 2 };

        // Function call
        if (areEqual(arr1, arr2))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
Python
# Python3 program for the above approach

# Returns true if arr1[0..N-1] and
# arr2[0..M-1] contain same elements.


def is_arr_equal(arr1, arr2):
        # Check if the length of arrays are
    # equal or not: A Easy Logic Check
    if len(arr1) != len(arr2):
        return False

    # Create a dict named count to
    # store counts of each element
    count = {}
    # Store the elements of arr1
    # and their counts in the dictionary
    for i in arr1:
        if i in count:
                # Element already in dict, simply increment its count
            count[i] += 1
        else:
                # Element found for first time, initialize it with value 1.
            count[i] = 1

    # Traverse through arr2 and compare
    # the elements and its count with
    # the elements of arr1
    for i in arr2:
        # Return false if the element
        # is not in count or if any element
        # appears more no. of times than in arr1
        if i not in count or count[i] == 0:
            return False
        else:
                # If element is found, decrement
                # its value in the dictionary
            count[i] -= 1
    # Return true if both arr1 and
    # arr2 are equal
    return True


# Driver Code
if __name__ == "__main__":
    arr1 = [3, 5, 2, 5, 2]
    arr2 = [2, 3, 5, 5, 2]

    if is_arr_equal(arr1, arr2):
        print("Yes")
    else:
        print("No")
C#
// C# program to find given two array
// are equal or not using hashing technique
using System;
using System.Collections.Generic;

class GFG {
    // Returns true if arr1[0..N-1] and arr2[0..M-1]
    // contain same elements.
    public static bool areEqual(int[] arr1, int[] arr2)
    {
        int N = arr1.Length;
        int M = arr2.Length;

        // If lengths of arrays are not equal
        if (N != M)
            return false;

        // Store arr1[] elements and their counts in
        // hash map
        Dictionary<int, int> map
            = new Dictionary<int, int>();
        int count = 0;
        for (int i = 0; i < N; i++) {
            if (!map.ContainsKey(arr1[i]))
                map.Add(arr1[i], 1);
            else {
                count = map[arr1[i]];
                count++;
                map.Remove(arr1[i]);
                map.Add(arr1[i], count);
            }
        }

        // Traverse arr2[] elements and check if all
        // elements of arr2[] are present same number
        // of times or not.
        for (int i = 0; i < N; i++) {
            // If there is an element in arr2[], but
            // not in arr1[]
            if (!map.ContainsKey(arr2[i]))
                return false;

            // If an element of arr2[] appears more
            // times than it appears in arr1[]
            if (map[arr2[i]] == 0)
                return false;

            count = map[arr2[i]];
            --count;

            if (!map.ContainsKey(arr2[i]))
                map.Add(arr2[i], count);
        }
        return true;
    }

    // Driver's code
    public static void Main(String[] args)
    {
        int[] arr1 = { 3, 5, 2, 5, 2 };
        int[] arr2 = { 2, 3, 5, 5, 2 };

        // Function call
        if (areEqual(arr1, arr2))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}

/* This code contributed by PrinciRaj1992 */
Javascript
<script>

//  Javascript program to find given two array
// are equal or not using hashing technique

    // Returns true if arr1[0..N-1] and arr2[0..M-1]
    // contain same elements.
    function areEqual(arr1, arr2)
    {
        let N = arr1.length;
        let M = arr2.length;
 
        // If lengths of arrays are not equal
        if (N != M)
            return false;
 
        // Store arr1[] elements and their counts in
        // hash map
        let map
            = new Map();
        let count = 0;
        for (let i = 0; i < N; i++) {
            if (map.get(arr1[i]) == null)
                map.set(arr1[i], 1);
            else {
                count = map.get(arr1[i]);
                count++;
                map.set(arr1[i], count);
            }
        }
 
        // Traverse arr2[] elements and check if all
        // elements of arr2[] are present same number
        // of times or not.
        for (let i = 0; i < N; i++) {
            // If there is an element in arr2[], but
            // not in arr1[]
            if (!map.has(arr2[i]))
                return false;
 
            // If an element of arr2[] appears more
            // times than it appears in arr1[]
            if (map.get(arr2[i]) == 0)
                return false;
 
            count = map.get(arr2[i]);
            --count;
            map.set(arr2[i], count);
        }
 
        return true;
    }
    
    // Driver code 
    
    let arr1 = [3, 5, 2, 5, 2];
    let arr2 = [2, 3, 5, 5, 2];
     
    // Function call
        if (areEqual(arr1, arr2))
            document.write("Yes");
        else
            document.write("No");
    
</script>

Output
Yes

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



Previous Article
Next Article

Similar Reads

Check if two arrays can be made equal by swapping pairs of one of the arrays
Given two binary arrays arr1[] and arr2[] of the same size, the task is to make both the arrays equal by swapping pairs of arr1[ ] only if arr1[i] = 0 and arr1[j] = 1 (0 ? i &lt; j &lt; N)). If it is possible to make both the arrays equal, print "Yes". Otherwise, print "No". Examples: Input: arr1[] = {0, 0, 1, 1}, arr2[] = {1, 1, 0, 0}Output: YesEx
11 min read
Find sub-arrays from given two arrays such that they have equal sum
Given two arrays A[] and B[] of equal sizes i.e. N containing integers from 1 to N. The task is to find sub-arrays from the given arrays such that they have equal sum. Print the indices of such sub-arrays. If no such sub-arrays are possible then print -1.Examples: Input: A[] = {1, 2, 3, 4, 5}, B[] = {6, 2, 1, 5, 4} Output: Indices in array 1 : 0, 1
15+ min read
Number of ways to select equal sized subarrays from two arrays having atleast K equal pairs of elements
Given two arrays A[] and B[], and an integer K, the task is to find the number of ways to select two subarrays of the same size, one from A and the other one from B such that the subarrays have at least K equal pairs of elements. (i.e. the number of pairs (A[i], B[j]) in the two selected subarrays such that A[i] = B[j] &gt;= K). Examples: Input: A[
13 min read
Minimize sum of product of same-indexed elements of two arrays by reversing a subarray of one of the two arrays
Given two equal-length arrays A[] and B[], consisting only of positive integers, the task is to reverse any subarray of the first array such that sum of the product of same-indexed elements of the two arrays, i.e. (A[i] * B[i]) is minimum. Examples: Input: N = 4, A[] = {2, 3, 1, 5}, B[] = {8, 2, 4, 3} Output: A[] = 1 3 2 5 B[] = 8 2 4 3 Minimum pro
12 min read
Minimum sum of two elements from two arrays such that indexes are not same
Given two arrays a[] and b[] of same size. Task is to find minimum sum of two elements such that they belong to different arrays and are not at same index in their arrays. Examples: Input : a[] = {5, 4, 13, 2, 1} b[] = {2, 3, 4, 6, 5}Output : 3We take 1 from a[] and 2 from b[]Sum is 1 + 2 = 3.Input : a[] = {5, 4, 13, 1} b[] = {3, 2, 6, 1}Output : 3
15+ min read
Check if two arrays can be made equal by reversing any subarray once
Given two arrays A[] and B[] of equal size N, the task is to check whether A[] can be made equal to B[] by reversing any sub-array of A only once. Examples: Input: A[] = {1, 3, 2, 4} B[] = {1, 2, 3, 4} Output: Yes Explanation: The sub-array {3, 2} can be reversed to {2, 3}, which makes A equal to B. Input: A[] = {1, 4, 2, 3} B[] = {1, 2, 3, 4} Outp
8 min read
Check if given two Arrays are equal (using Map)
Given two arrays, A[] and B[], the task is to check if they are equal or not. Arrays are considered equal if any permutation of array B equates to array A. Examples: Input: A[] = [2, 4, 5, 7, 5, 6] and B[] = [4, 2, 5, 5, 6, 7]Output: YesExplanation: All the elements in array A are present in array B and same number of times. Input: A[] = [2, 5, 8,
6 min read
Check if two arrays can be made equal by reversing subarrays multiple times
Given two arrays A[] and B[], the task is to check if array B can be made equal to A by reversing the subarrays of B by any number of times. Examples: Input: A[] = {1 2 3}, B[] = {3 1 2}Output: YesExplanation: Reverse subarrays in array B as shown below:Reverse subarray [3, 1], B becomes [1, 3, 2]Reverse subarray [3, 2], B becomes [1, 2, 3] = ATher
10 min read
Check if the sequence of elements in given two Arrays is same or not
Given two arrays A and B each of size N, the task is to check if the sequencing of both the arrays is the same or not. If the sequencing of both the arrays is same, the print Yes otherwise print No. Examples: Input: A[] = { 10, 12, 9, 11 }, B[] = { 2, 7, -3, 5 };Output: YesExplanation: In both the arrays 2nd element is greater than the first one.Th
5 min read
Check whether two strings can be made equal by reversing substring of equal length from both strings
Give two strings S1 and S2, the task is to check whether string S1 can be made equal to string S2 by reversing substring from both strings of equal length. Note: A substring can be reversed any number of times. Example: Input: S1 = "abbca", S2 = "acabb" Output: Yes Explanation: The string S1 and S2 can be made equal by: Reverse S1 in the range [2,
12 min read
Article Tags :