Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA Tutorial
  • Data Structures
  • Algorithms
  • Array
  • Strings
  • Linked List
  • Stack
  • Queue
  • Tree
  • Graph
  • Searching
  • Sorting
  • Recursion
  • Dynamic Programming
  • Binary Tree
  • Binary Search Tree
  • Heap
  • Hashing
  • Divide & Conquer
  • Mathematical
  • Geometric
  • Bitwise
  • Greedy
  • Backtracking
  • Branch and Bound
  • Matrix
  • Pattern Searching
  • Randomized
Open In App
Next Article:
C++ Program To Check Whether Two Strings Are Anagram Of Each Other
Next article icon

C++ Program to check if two Arrays are Equal or not

Last Updated : 05 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given two arrays arr1[] and arr2[] of length N and M respectively, the task is to check if the two arrays are equal or not. 

Note: Arrays are said to be equal if and only if both arrays contain the same elements and the frequencies of each element in both arrays are the same.

Examples:

Input: arr1[] = {1, 2, 3, 4, 5}, arr2[] = {5, 4, 3, 2, 1}
Output : Equal
Explanation: As both the arrays contain same elements.

Input: arr1[] = {1, 5, 2, 7, 3, 8}, arr2[] = {8, 2, 3, 5, 7, 1}
Output : Equal

 

Naive Approach: The basic way to solve the problem is as follows:

Apply sorting on both the arrays and then match each element of one array with the element at same index of the other array.

Follow the steps mentioned below to implement the idea.

  • Check if the length of both the arrays are equal or not
  • Then sort both the arrays, so that we can compare every equal element.
  • Linearly iterate over both the arrays and check if the elements are equal or not,
  • If equal then print Equal and if not then print Not equal.

Below is the implementation of the above approach:

C++
// C++ program to implement the approach  #include <bits/stdc++.h> using namespace std;  // Function to check if both arrays are equal bool checkArrays(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 elements are same     return true; }  // Driver Code int main() {     int arr1[] = { 1, 2, 3, 4, 5 };     int arr2[] = { 5, 4, 3, 2, 1 };     int N = sizeof(arr1) / sizeof(int);     int M = sizeof(arr2) / sizeof(int);      // Function call     if (checkArrays(arr1, arr2, N, M))         cout << "Equal";     else         cout << "Not Equal";     return 0; } 

Output
Equal

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

Efficient Approach: The problem can be solved efficiently using Hashing (unordered_map),

Use hashing to count the frequency of each element of both arrays. Then traverse through the hashtables of the arrays and match the frequencies of the elements.

Follow the below mentioned steps to solve the problem:

  • Check if the length of both the arrays are equal or not
  • Create an unordered map and store all elements and frequency of elements of arr1[] in the map.
  • Traverse over arr2[] and check if count of each and every element in arr2[] matches with the count in arr1[]. This can be done by decrementing the frequency while traversing in arr2[].

Below is the implementation of the above approach:

C++
// C++ program to implement the approach  #include <bits/stdc++.h> using namespace std;  // Function to check if both arrays are equal bool checkArrays(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 frequencies 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 Code int main() {     int arr1[] = { 1, 2, 3, 4, 5 };     int arr2[] = { 4, 3, 1, 5, 2 };     int N = sizeof(arr1) / sizeof(int);     int M = sizeof(arr2) / sizeof(int);      // Function call     if (checkArrays(arr1, arr2, N, M))         cout << "Equal";     else         cout << "Not Equal";     return 0; } 

Output
Equal

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


Next Article
C++ Program To Check Whether Two Strings Are Anagram Of Each Other
author
shadit13064
Improve
Article Tags :
  • C++ Programs
  • DSA
  • cpp-unordered_map

Similar Reads

  • C++ Program To Check if Two Matrices are Identical
    The below program checks if two square matrices of size 4*4 are identical or not. For any two matrices to be equal, the number of rows and columns in both the matrix should be equal and the corresponding elements should also be equal.  Recommended: Please solve it on "PRACTICE" first, before moving
    2 min read
  • C++ Program To Check If Two Linked Lists Are Identical
    Two Linked Lists are identical when they have the same data and the arrangement of data is also the same. For example, Linked lists a (1->2->3) and b(1->2->3) are identical. . Write a function to check if the given two linked lists are identical. Recommended: Please solve it on "PRACTICE
    3 min read
  • Program to check if an Array is Palindrome or not using STL in C++
    Given an array, the task is to determine whether an array is a palindrome or not, using STL in C++. Examples: Input: arr[] = {3, 6, 0, 6, 3} Output: Palindrome Input: arr[] = {1, 2, 3, 4, 5} Output: Not Palindrome Approach: Get the reverse of the Array using reverse() method, provided in STL.Initial
    2 min read
  • C++ Program To Check Whether Two Strings Are Anagram Of Each Other
    Write a function to check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, "abcd" and "dabc" are an anagram of each other. We strongly recommend that you
    7 min read
  • 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 < j < N)). If it is possible to make both the arrays equal, print "Yes". Otherwise, print "No". Examples: Input: arr1[]
    11 min read
  • C Program to check if two given strings are isomorphic to each other
    Given two strings str1 and str2, the task is to check if the two given strings are isomorphic to each other or not. Two strings are said to be isomorphic if there is a one to one mapping possible for every character of str1 to every character of str2 and all occurrences of every character in str1 ma
    2 min read
  • C++ Program to Print Even Numbers in an Array
    Given an array of numbers, the task is to print all the even elements of the array. Let us understand it with few examples mentioned below. Example: Input: num1 = [2,7,6,5,4] Output: 2, 6, 4 Input: num2 = [1,4,7,8,3] Output: 4, 81. Using for loop Approach: Iterate each element in the given using for
    5 min read
  • C++ Program to Find lost element from a duplicated array
    Given two arrays that are duplicates of each other except one element, that is one element from one of the array is missing, we need to find that missing element.Examples: Input: arr1[] = {1, 4, 5, 7, 9} arr2[] = {4, 5, 7, 9} Output: 1 1 is missing from second array. Input: arr1[] = {2, 3, 4, 5} arr
    5 min read
  • C++ Program to check if a matrix is symmetric
    A square matrix is said to be symmetric matrix if the transpose of the matrix is same as the given matrix. Symmetric matrix can be obtain by changing row to column and column to row. Examples:  Input : 1 2 3 2 1 4 3 4 3 Output : Yes Input : 3 5 8 3 4 7 8 5 3 Output : No A Simple solution is to do fo
    3 min read
  • How to Check if an Array is Empty in C++?
    In C++, arrays are fixed-size data structures that allow the users to store similar data in contiguous memory locations. In this article, we will learn how to check if an array is empty in C++. Example: Input:arr[]={}arr[]={1,2,3,4,5}Output:The array is emptyThe array is not emptyCheck if an Array i
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences