Check if an Array is mirror inverse or not

In this post we will discuss about the problem to check if the given array is a mirror inverse or not then we will write a C++ program to implement the same.

Given: An array arr[]

Problem: To check if the given array arr[] is mirror inverse or not.

Description: Inverse of an array is ‘if the array elements are swapped with their corresponding indices’.  If the inverse of an array is equals to the original array then it is known a mirror inverse.

Examples:

Input:

 arr[] = [3, 4, 2, 0, 1}

Output:

 Yes
In the given array:
index(0) -> value(3)
index(1) -> value(4)
index(2) -> value(2)
index(3) -> value(0)
index(4) -> value(1)
To find the inverse of the array, swap the index and the value of the array.
index(3) -> value(0)
index(4) -> value(1)
index(2) -> value(2)
index(0) -> value(3)
index(1) -> value(4)

Inverse arr[] = {3, 4, 2, 0, 1}
So, the inverse array is equal to the given array.

Input:

 arr[] = {1, 2, 3, 0}

Output:

 No

Solution:

  • Traverse through the array using loop for all indices.
  • if arr[arr[index]] = index  for all the positions then the given array is a mirror inverse.

C++ program to check if an Array is mirror inverse or not:

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

// Function that returns true if the array is mirror-inverse 
bool isMirrorInverse(int arr[], int n) 
{ 
    for (int i = 0; i < n; i++) 
    { 

        // If condition fails for any element 
        if (arr[arr[i]] != i) 
            return false; 
    } 

    // Given array is mirror-inverse 
    return true; 
} 

int main() 
{ 
        int arr[] = { 1, 2, 3, 0 }; 
        int n = sizeof(arr)/sizeof(arr[0]); 
        if (isMirrorInverse(arr,n)) 
            cout << "Yes"; 
        else
            cout << "No"; 
        return 0; 
} 

OUTPUT:

No

Comment below to discuss about the problem or to provide any suggestions.