Given two arrays arr1[] and arr2[] of size N and M respectively, the duty is to examine if the 2 arrays are equal or not.
Observe: Arrays are mentioned to be equal if and provided that each arrays include the identical parts and the frequencies of every factor in each arrays are the identical.
Examples:
Enter: arr1[] = {1, 2, 3, 4, 5}, arr2[] = {5, 4, 3, 2, 1}
Output : Equal
Clarification: As each the arrays include similar parts.Enter: arr1[] = {1, 5, 2, 7, 3, 8}, arr2[] = {8, 2, 3, 5, 7, 1}
Output : Equal
Naive Method: The essential method to remedy the issue is as follows:
Apply sorting on each the arrays after which match every factor of 1 array with the factor at similar index of the opposite array.
Comply with the steps talked about under to implement the thought.
- Examine if the size of each the arrays are equal or not
- Then type each the arrays, in order that we will examine each equal factor.
- Linearaly iterate over each the arrays and examine if the weather are equal or not,
- If equal then print Equal and if not then print Not equal.
Under is the implementation of the above strategy:
C++
|
Time Complexity: O(N * logN)
Auxiliary House: O(1)
Environment friendly Method: The issue may be solved effectively utilizing Hashing (unordered_map),
Use hashing to rely the frequency of every factor of each arrays. Then traverse by the hashtables of the arrays and match the frequencies of the weather.
Comply with the under talked about steps to unravel the issue:
- Examine if the size of each the arrays are equal or not
- Create an unordered map and retailer all parts and frequency of parts of arr1[] within the map.
- Traverse over arr2[] and examine if rely of each factor in arr2[] matches with the rely in arr1[]. This may be executed by decrementing the frequency whereas traversing in arr2[].
Under is the implementation of the above strategy:
C++
|
Time Complexity: O(N)
Auxiliary House: O(N)