Perfect Arrays


The task is to check if an array of size N is perfect, which means its reverse array is exactly the same as the original array. If the array is perfect, return True, otherwise return False.


Example 1:

Input: 
N=17
Arr= {15, 20, 5, 6, 5, 6, 13, 4, 3, 4, 13, 6, 5, 6, 5, 20, 15}
Output: true


Example 2:

Input: 
N=5
Arr= {1, 2, 3, 4, 5}
Output: false



method 1:

The method uses a for loop to iterate over the array a from index 0 to n-1. For each index i, it checks whether the element at index i is equal to the element at index n-1-i. If they are not equal, the method immediately returns false, indicating that the array is not perfect. If all the elements of the array are checked and none of them failed the equality test, the method returns true, indicating that the array is perfect.


Java implementation:

class codemummy{   
    public boolean IsPerfect(int a[], int n)
    {
        for(int i=0;i<n;i++){
           if(a[i]!=a[n-1-i])
           return false;
        }        
        return true;
    }   
}

 Time Complexity: O(n)
 Auxiliary Space: O(1).




c++ implementation:

#include <iostream> using namespace std; class codemummy { public: bool IsPerfect(int a[], int n) { for(int i=0;i<n;i++) { if(a[i] != a[n-1-i]) return false; } return true; } };

 Time Complexity: O(n)
 Auxiliary Space: O(1).




python implementation:

class codemummy:
    def IsPerfect(self, a, n):
        for i in range(n):
            if a[i] != a[n-1-i]:
                return False
        return True

 Time Complexity: O(n)
 Auxiliary Space: O(1).





No comments

darkmode