Program to check if an Array is Palindrome or not using STL in C++
Last Updated :
15 Dec, 2022
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.
- Initialise flag to unset int flag = 0.
- Loop the array till size n and check if the original array and the reversed array are same. If not set flag = 1
- After the loop has ended, If flag is set the print “Not Palindrome” else print “Palindrome”
Below is the implementation of above Approach:
CPP
#include <bits/stdc++.h>
using namespace std;
void palindrome( int arr[], int n)
{
int flag = 0;
int arr2[n];
memcpy (arr2, arr, n * sizeof ( int ));
reverse(arr, arr + n);
for ( int i = 0; i < n; i++)
if (arr[i] != arr2[i]) {
flag = 1;
break ;
}
if (flag == 0)
cout << "Palindrome\n";
else
cout << "Not Palindrome\n";
}
int main()
{
int arr[] = { 1, 2, 3, 2, 1 };
int n = sizeof (arr) / sizeof (arr[0]);
palindrome(arr, n);
return 0;
}
|
Time complexity: O(n)
Auxiliary space: O(n)
Related Articles:
Share your thoughts in the comments
Please Login to comment...