Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
C Program to check if an Array is Palindrome or not
Given an array arr[] of any size n, our task is to find out whether the array is palindrome or not. A palindrome is a sequence which reads the same backwards and forwards, like: MADAM, NAMAN, etc.
To check if an array is palindrome, we compare elements from both ends moving towards the center −
Syntax
int isPalindrome(int arr[], int n);
Example 1: Palindrome Array
#include <stdio.h>
int isPalindrome(int arr[], int n) {
int i, j;
for(i = 0, j = n - 1; i < j; i++, j--) {
if(arr[i] != arr[j]) {
return 0; // Not palindrome
}
}
return 1; // Palindrome
}
int main() {
int arr[] = {1, 2, 3, 2, 1};
int n = sizeof(arr) / sizeof(arr[0]);
if(isPalindrome(arr, n)) {
printf("Array is palindrome
");
} else {
printf("Array is not palindrome
");
}
return 0;
}
Array is palindrome
Example 2: Non-Palindrome Array
#include <stdio.h>
int isPalindrome(int arr[], int n) {
for(int i = 0; i < n / 2; i++) {
if(arr[i] != arr[n - 1 - i]) {
return 0;
}
}
return 1;
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Array: ");
for(int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("
");
if(isPalindrome(arr, n)) {
printf("Array is palindrome
");
} else {
printf("Array is not palindrome
");
}
return 0;
}
Array: 1 2 3 4 5 Array is not palindrome
How It Works
The algorithm compares elements from both ends of the array moving towards the center:
-
Two-pointer approach: Use indices
iandjstarting from opposite ends -
Comparison: Check if
arr[i] == arr[j]at each step - Early termination: If any pair doesn't match, return false immediately
- Time complexity: O(n/2) which is O(n)
- Space complexity: O(1) − constant extra space
Key Points
- Only need to check up to the middle of the array (
n/2comparisons) - Arrays with single element or empty arrays are considered palindromes
- The function returns 1 for palindrome and 0 for non-palindrome
Conclusion
Checking if an array is palindrome involves comparing elements from both ends moving towards the center. This two-pointer approach provides an efficient O(n) solution with constant space complexity.
Advertisements
