Given a string s, the task is to check if it is palindrome or not.
Example:
Input: s = "abba"
Output: true
Explanation: s is a palindrome
Input: s = "abc"
Output: false
Explanation: s is not a palindrome
Using Two-Pointers - O(n) time and O(1) space
The idea is to keep two pointers, one at the beginning (left) and the other at the end (right) of the string.
- Then compare the characters at these positions. If they don't match, the string is not a palindrome, and return 0.
- If they match, the pointers move towards each other (left pointer moves right, right pointer moves left) and continue checking.
- If the pointers cross each other without finding a mismatch, the string is confirmed to be a palindrome, and returns 1.
Working:
Using Single Variable - O(n) time and O(1) space
This approach is just an optimization of two variables that we have used in the above approach. Here, we can do the same with the help of single variable only. The idea is that:
- Iterates through the first half of the string.
- For each character at index i, checks if s[i] and s[length - i - 1])
- If any pair of characters don't match, then returns 0.
- If all characters match, then returns 1 (indicating the string is a palindrome).
Using Recursion - O(n) time and O(n) space
This approach is similar to our two pointers approach that we have discussed above. Here, we can use recursion to check the first and last letters of a string and then recursively check for remaining part of the string.
- Base case: if the length of the string is 1 or less, it's considered a palindrome.
- If the first and last characters don't match, it's not a palindrome, return 0.
- Otherwise, recursively calls itself by incrementing left by 1 and decrementing right by 1
Time Complexity: O(n), Each character is checked once, and there are O(n/2) recursive calls.
Auxiliary Space: O(n), due to recursive call stack
By Reversing String - O(n) time and O(n) space
According to the definition of a palindrome, a string reads the same both forwards and backwards. So, we can use this idea and compare the reversed string with the original one.
- If they are the same, the string is a palindrome, and then returns 1.
- If they are different, then returns 0, meaning it's not a palindrome.
Related Article: