Check if an Array is Palindrome in C++

This tutorial will discuss about a unique way to check if array is palindrome in C++.

Video Tutorial : Check if an Array is Palindrome using STL Algorithm std::equal()

To check if an array is palindrome or not, we need to comprare the first half of array with the reversed second half of array.

For example, suppose our array is,

int arr[] = {9, 5, 4, 3, 2, 3, 4, 5, 9};

Now to check if this array is a palindrome or not. We need to compare,

  • 1st element of array with the last element of array.
  • 2nd element of array with the second last element of array.
  • ith element of array with the ith element from last in array.

This can be done using the STL Algorithm std::equal().

In the std::equal() function, pass three arguments i.e.

  • Pointer to the start of array i.e. arr
  • Pointer to the middle of array i.e. arr + len/2
  • A reverse iterator pointing to the end of array i.e. std::reverse_iterator<int*>(arr + len)

It will compare all the elements from arr to arr + len/2, with the second half of array using reverse iterator. It will return truw if the first half of array is equal to the reversed second half of array.

Let’s see the complete example,

#include <iostream>
#include <algorithm>

int main()
{
    int arr[] = {9, 5, 4, 3, 2, 3, 4, 5, 9};

    // Get the length of array
    size_t len = sizeof(arr)/sizeof(arr[0]);

    // Compare the first half of array with the
    // reversed second half of array
    bool result = std::equal(arr,
                             arr + len/2,
                             std::reverse_iterator<int*>(arr + len));

    // Check if array is Palindrome or not
    if(result)
    {
        std::cout<< "Yes, Array is a Palindrome." << std::endl;
    }
    else
    {
        std::cout<< "No, Array is not a Palindrome." << std::endl;
    }
    return 0;
}

Output :

Yes, Array is a Palindrome.

Summary

Today we learned about a way to check if array is palindrome in C++. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top