Check If the Given Array is Mirror Inverse in Java
It is a very interesting problem frequently asked in interviews of top IT companies like Google, Amazon, TCS, Accenture, etc. By solving the problem, one wants to check the logical ability, critical thinking, and problem-solving skill of the interviewee. So, in this section, we are going to check if the given array is mirror inverse or not in Java with different approaches and logic. Also, we will create Java programs for the same.
Problem Statement
We have given an array named a[], the task is to find whether the array is mirror inverse or not. If an array is mirror-inverse then print Yes else print No.
Reverse of Array
The reverse of an array can be found by writing the array right to left.
Example:
Mirror Inverse of Array
If we swap array indices with corresponding array elements and rewrite the array values. If we get its inverse is equal to the given array, the array is called the mirror inverse. Let’s understand it through examples.
Note: Reverse and mirror inverse array are not the same.
Example 1:
Input: arr[] = [3, 4, 2, 0, 1, 5, 6}
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)
index(5) -> value(5)
index(6) -> value(6)
In order to find the inverse of the array, swap the index and the value of the given array. Hence, we get:
index(3) -> value(0)
index(4) -> value(1)
index(2) -> value(2)
index(0) -> value(3)
index(1) -> value(4)
index(5) -> value(5)
index(6) -> value(6)
Inverse arr[] = {3, 4, 2, 0, 1, 5, 6}
We observe that the inverse array is equal to the given array. So, it is a mirror inverse of the given array.
Example 2:
Input: arr[] = {1, 3, 5, 7, 9}
index(0) -> value(1)
index(1) -> value(3)
index(2) -> value(5)
index(3) -> value(7)
index(4) -> value(9)
In order to find the inverse of the array, swap the index and the value of the given array. Hence, we get:
index(1) -> value(0)
index(3) -> value(1)
index(5) -> value(2)
index(7) -> value(3)
index(9) -> value(4)
Inverse arr[] = {0, 1, 2, 3, 4}
We observe that the inverse array is not equal to the given array. So, it is not a mirror inverse of the given array.
Java Program to Check if the Given Array is a Mirror Inverse or Not
- create a new array by swapping the value of the array and indices of the given array.
- Compare both arrays. If the new array is equal to the original one, the given array is a mirror inverse.
MirrorInverseArray1.java
Output:
No
Let’s see another approach.
Another approach is that traverse over the given array and for all the indices if the condition array[array[index]] = index satisfies then the given array is mirror inverse. The approach is better than the above approach.
MirrorInverseArray2.java
Output:
The given array is mirror inverse.