Write a program to determine whether a given string is palindrome. A palindromic string is a string that remains the same with its characters reversed. Like ABCBA, for example, is “symmetrical”.

Practice this problem

A simple solution would be to reverse the string and compare if the original string is equal to the reversed string or not. If strings are found to be equal, we can say that the given string is a palindrome. This solution, though concise and straightforward, is not in-place. Also, the comparison function might end up iterating till the end of the string. This solution is linear on paper, but we can still do better.

 
We can easily check for palindromic string in-place without using extra string and without iterating through the complete string. The idea is to take two pointers that point at the beginning and end of the string and start comparing characters pointed by them. The first iteration will check if the first and last characters are the same, and the next iteration will compare the next pair and so on. If a mismatch happens at any point, we can say that the given string is not a palindrome.

Iterative Version

The iterative implementation can be seen below in C++, Java, and Python:

C++


Download  Run Code

Output:

Palindrome

Java


Download  Run Code

Output:

Palindrome

Python


Download  Run Code

Output:

Palindrome

Recursive Version

The recursive implementation can be seen below in C++, Java, and Python:

C++


Download  Run Code

Output:

Palindrome

Java


Download  Run Code

Output:

Palindrome

Python


Download  Run Code

Output:

Palindrome

We can also rewrite the above recursive code in a single line (remember, an interviewer can ask this as a follow-up question or even start with this problem itself).

C++


Download  Run Code

Output:

Palindrome

Java


Download  Run Code

Output:

Palindrome

Python


Download  Run Code

Output:

Palindrome

The time complexity of all above-discussed methods is O(n), where n is the length of the input string. The iterative version doesn’t require any extra space, whereas the recursive version requires O(n) implicit space for the call stack.