Table of contents
1.
Introduction
2.
Idea Behind the Problem
2.1.
Brute Force Method
2.1.1.
Approach
2.1.2.
Brute Force Pseudocode
2.1.3.
Brute Force Complexities
2.2.
Hashing Method
2.2.1.
Approach
2.2.2.
Hashing Pseudocode
2.2.3.
Hashing Complexities
3.
Understand with Example
4.
Code in C++ 👩🏻‍💻
4.1.
Output
5.
Code in Java 👩🏻‍💻
5.1.
Output
6.
Code in Python 👩🏻‍💻
6.1.
Output
7.
Frequently Asked Questions
7.1.
How is this problem solved using brute force?
7.2.
What is an array?
7.3.
Define what is meant by hashing.
7.4.
Describe the differences between a map and a set.
7.5.
Why is hashing better than the brute force approach in array comparison?
8.
Conclusion
Last Updated: Mar 27, 2024
Easy

Check if Two Arrays are Equal or Not

Author Sneha Mallik
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this article, we will discuss the problem to check if two arrays are equal or not and briefly discuss the approach to be used and its time and space complexity. 

Problem Statement Title

Before discussing the problem statement to check if two arrays are equal or not, let us first discuss what an array means.

Array: It is a linear data structure consisting of a collection of values called elements of an array, stored in a contiguous memory location and can be accessed using array indexes.

Person coding image

In this article, we will look at how to solve the problem statement to check if two arrays are equal or not, alongside an example.

Idea Behind the Problem

The task is to determine whether or not two arrays of identical lengths are equal. When two arrays have the same set of items, they are said to be equal; the arrangements (or permutations) of the elements, however, may differ.

Idea Thinking image

Remember that the count of repeated elements must match if there are repetitions for two arrays to be equal.

Brute Force Method

The basic concept is to arrange the elements in both arrays in either increasing or decreasing order and then determine whether or not they are the same at each place.

Approach

  • We measure the length of both arrays. The function will return false if they aren't the same.
     
  • We will then sort both the arrays using an efficient O(N log N) sorting algorithm.
     
  • Now, we will run a loop across both arrays, comparing values at each index. If any element doesn't match, it will return false. Or else return true at the ending of the loop. 
     

Brute Force Pseudocode

/*
   Brute force pseudocode to check if two arrays are equal or not.
*/

bool ifArrayEqual(int firstArray[], int secondArray[], int a, int b)
{
   if (a != b)
       return false
   heapSort(firstArray, a)
   heapSort(secondArray, b)
   for (int i = 0; i < a; i = i+1)
   {
       if (firstArray[i] != secondArray[i])
           return false
   }       
   return true
}

Brute Force Complexities

  • We only perform one comparison if the sizes of the two arrays are not equal, i.e., a != b, then time complexity = O(1).
     
  • If the size of both arrays is identical, i.e., a == b, then the time complexity 
    = Time complexity of sorting firstArray[] + Time complexity of sorting secondArray[] + Time complexity of comparing both arrays
    = O(aloga) + O(blogb) + O(a)
    = O(aloga + blogb), i.e., O(NlogN + NlogN)
    = O(NlogN)
     
  • Space complexity = O(1) if we employ an in-place sorting technique like heap sort.

Hashing Method

To reduce the complexity of the problem, we will use an unordered map, which is implemented using a hash table in hashing method. The concept is that both arrays must have equal elements if their frequency counts are also equal for all members in both arrays. Therefore, we require an efficient method for storing and searching variables based on their frequency count.

Since it efficiently completes insert and search operations in O(1) on average, the hash table is a perfect solution to this issue.

Approach

  • We will create a hash table ‘ht’ of size ‘a’. Each element of the array ‘firstArray[]’ serves as a key and the frequency count serves as its value in a hash table ‘ht’ that we generated.
     
  • The frequency count of each element is recorded in the hash table as we scan the array ‘firstArray[]’. In other words, we add 1 to the frequency count of any ‘firstArray[i]’ that repeats in the hash table.
     
  • Now, we search each ‘secondArray[i]’ element in the hash table by scanning the array ‘secondArray[]’. If it is absent, the first mismatch will occur, and both arrays will not be equal. Thus, we return false.
     
  • We decrease the specific frequency count of the value ‘secondArray[i]’ by 1 if it appears in the hash table. In the hash table, if any element's frequency count reaches 0, it signifies that element ‘secondArray[i]’ appears more frequently in ‘secondArray[]’ than it does in ‘firstArray[]’. Thus, we return false because the two arrays are not identical.
     
  • For each component in array ‘secondArray[]’, the same procedure is repeated. Both arrays are equal if we reach the end of the loop; therefore, we return true.
     

Let us take an example of two arrays as input each of size = 3 for ‘firstArray’ and ‘secondArray’.
[Note that if the sizes of both arrays are not equal then the function will return with boolean value ‘false’. Hence, the output will be printed as ‘False, the two arrays are not equal.’]

Now, when the size of the arrays is equal, the function will compare the two arrays in the following way:

firstArray[]={1, 8, 2}

secondArray[]={2, 1, 8}
In the beginning, we will store the ‘firstArray’ elements in the hashtable along with their frequencies.

Hash Table storing First Array Elements

Now we will check the ‘secondArray’ elements with the ‘firstArray’ elements in the hashtable.

In the loop, for i=0 and i<3:

Step 1 of comparison of elements

For i=1 and i<3:

Step 2 of comparison of elements

For i=2 and i<3:

Step 3 of comparison of elements

Now, in the end, since no elements are present in the ‘secondArray’ to check the occurrences as ‘i’ cannot be equal to or more than 3, the boolean function will return ‘true’. 

Hence, the output will be: True, the two arrays are equal.
Other cases of the boolean function ‘ifArrayEqual’ returning ‘false’ occurs when the frequencies mismatch between the arrays.

Hashing Pseudocode

/*
   Hashing pseudocode to check if two arrays are equal or not.
*/

bool ifArrayEqual(int firstArray[], int secondArray[], int a, int b)
{
   if (a != b)
       return false
   unordered_map<int, int> ht
   for (int i = 0; i < a; i = i+1)
   {
       ht[firstArray[i]] = ht[secondArray[i]] + 1
   }
   for (int i = 0; i < a; i = i + 1)
   {
       if (ht.find(secondArray[i]) == ht.end())
           return false
       if (ht[secondArray[i]] == 0)
           return false
       ht[secondArray[i]] =  ht[secondArray[i]] - 1
   } 
   return true
}

Hashing Complexities

  • The hash table's insert and search operations take an average of O(1) time to complete.
     
  • Each iteration of our two independent loops involves performing O(1) operations. So, on average, time complexity 
    = a*O(1) + a*O(1) 
    = O(a), i.e., O(N).
     
  • For storing a hash table of size ‘N’, the space complexity is O(N).

Understand with Example

We will look at some examples of checking if the two arrays are equal or not. We will print “True” if the arrays are equal, or else we will print out “False” if they are not equal.

Input and Output

Let's explore the hashing method's code for the given problem statement in C++, Java, and Python.

You can also read about the Longest Consecutive Sequence.

Code in C++ 👩🏻‍💻

/*
  Program in C++ to check if two arrays are equal or not using hashing method.
*/

#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;

/*
  This function will return "true" if firstArray[] and secondArray[] have the
  same elements.
*/
bool ifArrayEqual(int firstArray[], int secondArray[], int a, int b)
{
   // To check if the lengths of firstArray[] and secondArray[] are equal.
   if (a != b)
   {
      return false;
   }
   
   /*
       To store the firstArray[] elements and their respective frequency count
       in hashmap.
   */
   unordered_map<int, int> ht;
   for (int i = 0; i < a; i++)
   {
      ht[firstArray[i]]++;
   }
   
   /*
      To traverse through the secondArray[] elements and find if their occurrence
      is the same number of times or not.
   */
   for (int i = 0; i < a; i++) {
       /*
           To check if an element is present in secondArray[], but absent in
           firstArray[].
       */
       if (ht.find(secondArray[i]) == ht.end())
           return false;

       /*
           To check if an element appears more times in secondArray[] than it
           appears in firstArray[].
       */
       if (ht[secondArray[i]] == 0)
          return false;
    
       // To decrease the count of secondArray[] elements in the unordered map.
       ht[secondArray[i]]--;
   }
   return true;
}

// Driver Code
int main()
{
   int m, n;
   cout << "\nEnter the size of arrays : ";
   cin >> m >> n;
    int firstArray[m], secondArray[n];
   cout << "\nEnter the first array elements : ";
   for(int i=0; i<m; i++)
   {
       cin >> firstArray[i];
   }
    cout << "\nEnter the second array elements : ";
   for(int i=0; i<n; i++)
   {
       cin >> secondArray[i];
   }
   int a = sizeof(firstArray) / sizeof(int);
   int b = sizeof(secondArray) / sizeof(int);
   if (ifArrayEqual(firstArray, secondArray, a, b))
   {
       cout << "\nTrue, the two arrays are equal.\n";
   }
   else
   {
       cout << "\nFalse, the two arrays are not equal.\n";
   }
   return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output

Cpp Output if not equal

Cpp Output if equal

Code in Java 👩🏻‍💻

/*
 Program in Java to check if two arrays are equal or not using hashing method.
*/

import java.util.*;
class Main {
   /*
     This function will return "true" if firstArray[] and secondArray[] have the
     same elements.
   */
   public static boolean ifArrayEqual(int firstArray[], int secondArray[])
   {
       int a = firstArray.length;
       int b = secondArray.length;
       // To check if the lengths of firstArray[] and secondArray[] are equal.
       if (a != b)
           return false;
           
       /*
         To store the firstArray[] elements and their respective frequency count
         in hashmap.
       */
       Map<Integer, Integer> map = new HashMap<Integer, Integer>();
       int cnt = 0;
       for (int i = 0; i < a; i++) {
           if (map.get(firstArray[i]) == null)
           {
               map.put(firstArray[i], 1);
           }
           else
           {
               cnt = map.get(firstArray[i]);
               cnt++;
               map.put(firstArray[i], cnt);
           }
       }
       
       /*
         To traverse through the secondArray[] elements and find if their
         occurrence is the same number of times or not.
       */
       for (int i = 0; i < a; i++) {
           /*
             To check if an element is present in secondArray[], but absent in
             firstArray[].
           */
           if (!map.containsKey(secondArray[i]))
               return false;
               
           /*
             To check if an element appears more times in secondArray[] than it
             appears in firstArray[].
           */
           if (map.get(secondArray[i]) == 0)
               return false;
           cnt = map.get(secondArray[i]);

           // To decrease the count of secondArray[] elements in the hashmap.
           --cnt;
           map.put(secondArray[i], cnt);
       }
       return true;
   }
   
   // Driver code
   public static void main(String[] args)
   {
     Scanner sc=new Scanner(System.in);
     try{
     System.out.print("\nEnter the size of arrays : ");
     int m = sc.nextInt();
     int n = sc.nextInt();
      
       int firstArray[] = new int[m];
       System.out.println("\nEnter the first array elements : "); 
       for(int i=0; i<m; i++) 
       {   
         firstArray[i] = sc.nextInt(); 
       }
      
       int secondArray[] = new int[n];
       System.out.println("\nEnter the second array elements : "); 
       for(int i=0; i<n; i++) 
       {   
         secondArray[i] = sc.nextInt(); 
       }

       if (ifArrayEqual(firstArray, secondArray))
           System.out.println("\nTrue, the two arrays are equal.\n");
       else
           System.out.println("\nFalse, the two arrays are not equal.\n");
     }
     finally {
       sc.close();
     }
   }
}
You can also try this code with Online Java Compiler
Run Code

Output

Java Output if equal

Java Output if not equal

Code in Python 👩🏻‍💻

'''
   Program in Python to check if two arrays are equal or not using hashing method.
'''
from collections import defaultdict


# This function will return "true" if firstArray[] and secondArray[]
# have the same elements.
def ifArrayEqual(firstArray, secondArray, a, b):

   # To check if the lengths of firstArray[] and secondArray[] are equal.
   if (a != b):
       return False

   # To store the counts we create the defaultdict.
   cnt = defaultdict(int)

   # To store the firstArray[] elements and their respective frequency
   # count in the default dictionary.
   for i in firstArray:
       cnt[i] += 1

   # To traverse through the secondArray[] elements
   # and compare its count with the elements of firstArray[].
   for i in secondArray:

       # To return false if the element is not in secondArray[]
       # or if any element appears more number of times than in firstArray[].
       if (cnt[i] == 0):
           return False

       # To decrease the count of secondArray[] elements in the dictionary.
       else:
           cnt[i] -= 1

   # Return true if both firstArray[] and secondArray[] are equal
   return True


# Driver Code
if __name__ == '__main__':
   m=int(input("\nEnter the size of first array : "))
   n=int(input("\nEnter the size of second array : "))
   firstArray=list(map(int, input("\nEnter the first array elements : ").strip().split()))
   secondArray=list(map(int, input("\nEnter the second array elements : ").strip().split()))

a = len(firstArray)
b = len(secondArray)

if ifArrayEqual(firstArray, secondArray, a, b):
   print("\nTrue, the two arrays are equal.\n")
else:
   print("\nFalse, the two arrays are not equal.\n")
You can also try this code with Online Python Compiler
Run Code

Output

Python Output if not equal

Python Output if equal

Frequently Asked Questions

How is this problem solved using brute force?

The basic concept of solving the problem statement “to check if two arrays are equal or not” is to arrange the elements in both arrays in either increasing or decreasing order and then determine whether or not they are the same at each place. 
A better efficient approach is to solve this problem by using hashing method.

What is an array?

An array is a group of related values kept in consecutive memory addresses. Each value is set at each step, similar to a staircase, and elements can be accessed by knowing the stair number (or index number).

Define what is meant by hashing.

The process of hashing allows for the transformation of one value into another. It facilitates and speeds up searching.

Describe the differences between a map and a set.

While a map provides an interface for storing key-value pairs, a set is a collection of data that cannot contain duplicate entries.

Why is hashing better than the brute force approach in array comparison?

The brute force approach has a time complexity of O(N logN) whereas the hashing approach has O(N) time complexity and we know that O(N) < O(N logN) as when ‘N’ increases in value, N*logN value becomes greater than N. Therefore, hashing method is better.

Conclusion

In this blog, we learned about the problem statement to check if two arrays are equal or not. Using an example, we discussed the topic and explained the algorithm's time and space complexity as well as the program's output based on user input.

Check out here for similar problem statement blogs:

Recommended problems -

 

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, JavaScript, System Design, DBMS, Java, etc. Enroll in our courses and refer to the mock test and problems available. Take a look at the interview experiences and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow. 🥷✨

Thank you

Happy Learning, Ninja!

Live masterclass