![]() |
VOOZH | about |
A string is said to be palindrome if the reverse of the string is the same as the string. In this article, we will learn how to check whether the given string is palindrome or not using C program.
The simplest method to check for palindrome string is to reverse the given string and store it in a temporary array and then compare both of them using strcmp() function. If they are equal, then the string is palindrome, otherwise, it is not. Let's look at its implementation.
"madam" is palindrome. "hello" is not palindrome.
Time Complexity: O(n), where n is the length of the string.
Auxiliary Space: O(n), for storing the reversed string.
Checking for a palindrome in C is a great exercise for string manipulation.
In this method, two index pointers are taken: one pointing to the first character and other pointing to the last character in the string. The idea is to traverse the string in forward and backward directions simultaneously while comparing characters at the same distance from start and end.
Let's take a look at its implementation:
"madam" is palindrome. "hello" is not palindrome.
Time complexity: O(n), where n is the number of characters in the string.
Auxiliary Space: O(1)
Two-pointer approach can also be implement using recursion. The current first and last index pointers (representing the current first and last characters) can be passed to the function as arguments.
"madam" is palindrome. "hello" is not palindrome.
Time complexity: O(n), where n is the number of characters in the string.
Auxiliary Space: O(n), due to recursive stack space.