Problem Statement:
Given an unsorted array, check if it is palindrome array or not.
Example:
arr[] = {1, 2, 0, 2, 1}
Output: Palindrome
Solution:
The solution is very simple, below are the steps to be follow:
1. We take 2 pointer, first pointer will point to beginning of the array, second pointer will point to the end of the array
2. Then we check if both of the elements are same, if they are same then we increment the first pointer and decrement the second pointer. And repeat Step 1 and 2.
3. We repeat the steps till we reach the mid of the array.
4. If they are not same, then we break the array.
Solution in C++
#include <vector>
#include <algorithm>
//visit www.ProDeveloperTutorial.com for 450+ solved questions
#include <iostream>
#include <queue>
using namespace std;
void check_if_palindrome(int arr[], int n)
{
// Loop the array till the mid n/2.
for (int i = 0; i <= n / 2 && n != 0; i++)
{
// if the elements are not same, then print its not a palindrome and exit.
if (arr[i] != arr[n - i - 1])
{
cout << "Array is Not Palindrome"<<endl;
return;
}
}
cout << "Array is Palindrome"<<endl;
return;
}
// Driver code.
int main()
{
int arr[] = { 10, 20, 30, 20, 10 };
int n = sizeof(arr) / sizeof(arr[0]);
check_if_palindrome(arr, n);
return 0;
}
Output:
Array is Palindrome