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 palindromeInput: s = "abc"
Output: false
Explanation: s is not a palindrome
Table of Content
Using Two-Pointers - O(n) time and O(1) space
A palindrome reads the same from both ends. By comparing characters from the beginning and the end simultaneously, we can quickly determine whether the string is a palindrome.
- Initialize two pointers, one at the beginning and the other at the end of the string.
- Compare the characters at both pointers.
- If they differ, return false.
- Otherwise, move both pointers towards the center.
- If all corresponding characters match, return true.
Working:
#include <bits/stdc++.h>
using namespace std;
bool isPalindrome(string &s) {
// Initialize two pointers: one at the beginning (left)
// and one at the end (right)
int left = 0;
int right = s.length() - 1;
// Continue looping while the two pointers
// have not crossed each other
while (left < right) {
// If the characters at the current positions are not equal,
// return false (not a palindrome)
if (s[left] != s[right])
return false;
// Move the left pointer to the right
// and the right pointer to the left
left++;
right--;
}
// If no mismatch is found,
// return true (the string is a palindrome)
return true;
}
int main() {
string s = "abba";
cout << boolalpha << isPalindrome(s) << endl;
return 0;
}
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool isPalindrome(char s[]) {
int left = 0;
int right = strlen(s) - 1;
// Continue looping while the two pointers have not crossed
while (left < right) {
// If the characters at the current positions
// are not equal
if (s[left] != s[right])
return false;
// Move the left pointer to the right and
// the right pointer to the left
left++;
right--;
}
// If no mismatch is found, return true (palindrome)
return true;
}
int main() {
char s[] = "abba";
printf("%s\n", isPalindrome(s) ? "true" : "false");
return 0;
}
class GFG {
public static boolean isPalindrome(String s) {
int left = 0;
int right = s.length() - 1;
// Continue looping while the two pointers
// have not crossed
while (left < right) {
// If the characters at the current positions
// are not equal
if (s.charAt(left) != s.charAt(right))
return false;
// Move the left pointer to the right and
// the right pointer to the left
left++;
right--;
}
// If no mismatch is found, return true (palindrome)
return true;
}
public static void main(String[] args) {
String s = "abba";
System.out.println(isPalindrome(s));
}
}
def isPalindrome(s):
left = 0
right = len(s) - 1
# Continue looping while the two pointers
# have not crossed
while left < right:
# If the characters at the current positions
# are not equal
if s[left] != s[right]:
return False
# Move the left pointer to the right and
# the right pointer to the left
left += 1
right -= 1
# If no mismatch is found, return True (palindrome)
return True
s = "abba"
print(isPalindrome(s))
using System;
class GFG {
static bool isPalindrome(string s) {
int left = 0;
int right = s.Length - 1;
// Continue looping while the two pointers
// have not crossed
while (left < right) {
// If the characters at the current positions
// are not equal
if (s[left] != s[right])
return false;
// Move the left pointer to the right and
// the right pointer to the left
left++;
right--;
}
// If no mismatch is found, return true (palindrome)
return true;
}
static void Main() {
string s = "abba";
Console.WriteLine(isPalindrome(s));
}
}
function isPalindrome(s) {
let left = 0;
let right = s.length - 1;
// Continue looping while the two pointers
// have not crossed
while (left < right) {
// If the characters at the current positions
// are not equal
if (s[left] !== s[right]) {
return false;
}
// Move the left pointer to the right and
// the right pointer to the left
left++;
right--;
}
// If no mismatch is found, return true (palindrome)
return true;
}
// Driver code
const s = "abba";
console.log(isPalindrome(s));
Output
true
Using Single Variable - O(n) time and O(1) space
Since every character only needs to be compared with its corresponding character from the other end, a single loop over the first half of the string is sufficient.
- Iterate from the beginning to the middle of the string.
- Compare the current character with its corresponding character from the end.
- If they differ, return
false. - If all pairs match, return
true.
#include <bits/stdc++.h>
using namespace std;
bool isPalindrome(string &s) {
int len = s.length();
// Iterate over the first half of the string
for (int i = 0; i < len / 2; i++) {
// If the characters at symmetric positions are not equal
if (s[i] != s[len - i - 1])
// Return false (not a palindrome)
return false;
}
// If all symmetric characters are equal,
// then it is a palindrome
return true;
}
int main() {
string s = "abba";
cout << boolalpha << isPalindrome(s) << endl;
return 0;
}
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool isPalindrome(char s[]) {
int len = strlen(s);
// Iterate over the first half of the string
for (int i = 0; i < len / 2; i++) {
// If the characters at symmetric positions are not equal
if (s[i] != s[len - i - 1])
// Return false (not a palindrome)
return false;
}
// If all symmetric characters are equal,
// then it is a palindrome
return true;
}
int main() {
char s[] = "abba";
printf("%s\n", isPalindrome(s) ? "true" : "false");
return 0;
}
class GFG {
public static boolean isPalindrome(String s) {
int len = s.length();
// Iterate over the first half of the string
for (int i = 0; i < len / 2; i++) {
// If the characters at symmetric positions are
// not equal
if (s.charAt(i) != s.charAt(len - i - 1))
// Return false (not a palindrome)
return false;
}
// If all symmetric characters are equal,
// then it is a palindrome
return true;
}
public static void main(String[] args) {
String s = "abba";
System.out.println(isPalindrome(s));
}
}
def isPalindrome(s):
length = len(s)
# Iterate over the first half of the string
for i in range(length // 2):
# If the characters at symmetric positions are not equal
if s[i] != s[length - i - 1]:
# Return False (not a palindrome)
return False
# If all symmetric characters are equal,
# then it is a palindrome
return True
s = "abba"
print(isPalindrome(s))
using System;
class GFG {
static bool isPalindrome(string s) {
int len = s.Length;
// Iterate over the first half of the string
for (int i = 0; i < len / 2; i++) {
// If the characters at symmetric positions are
// not equal
if (s[i] != s[len - i - 1])
// Return false (not a palindrome)
return false;
}
// If all symmetric characters are equal,
// then it is a palindrome
return true;
}
static void Main() {
string s = "abba";
Console.WriteLine(isPalindrome(s));
}
}
function isPalindrome(s) {
let len = s.length;
// Iterate over the first half of the string
for (let i = 0; i < len / 2; i++) {
// If the characters at symmetric
// positions are not equal
if (s[i] !== s[len - i - 1]) {
// Return false (not a palindrome)
return false;
}
}
// If all symmetric characters are equal,
// then it is a palindrome
return true;
}
// Driver code
let s = "abba";
console.log(isPalindrome(s));
Output
true
Using Recursion - O(n) time and O(n) space
A palindrome has matching characters at equal distances from the beginning and the end. We can recursively compare these pairs until we reach the middle of the string.
- Start with two indices at the beginning and the end of the string.
- If the characters at these indices differ, return
false. - If the indices meet or cross each other, return
true. - Otherwise, recursively check the remaining substring by moving both indices towards the center.
#include <bits/stdc++.h>
using namespace std;
bool isPalindromeUtil(string &s, int left, int right) {
// Base case
if (left >= right)
return true;
// If the characters at the current positions are not equal,
// it is not a palindrome
if (s[left] != s[right])
return false;
// Move left pointer to the right
// and right pointer to the left
return isPalindromeUtil(s, left + 1, right - 1);
}
bool isPalindrome(string s) {
int left = 0, right = s.length() - 1;
return isPalindromeUtil(s, left, right);
}
int main() {
string s = "abba";
cout << boolalpha << isPalindrome(s) << endl;
return 0;
}
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool isPalindromeUtil(char *s, int left, int right) {
// Base case
if (left >= right)
return true;
// If the characters at the current positions are not equal,
// it is not a palindrome
if (s[left] != s[right])
return false;
// Move left pointer to the right
// and right pointer to the left
return isPalindromeUtil(s, left + 1, right - 1);
}
bool isPalindrome(char *s) {
int left = 0;
int right = strlen(s) - 1;
return isPalindromeUtil(s, left, right);
}
int main() {
char s[] = "abba";
printf("%s\n", isPalindrome(s) ? "true" : "false");
return 0;
}
class GFG {
static boolean isPalindromeUtil(String s, int left, int right) {
// Base case
if (left >= right)
return true;
// If the characters at the current positions are
// not equal, it is not a palindrome
if (s.charAt(left) != s.charAt(right))
return false;
// Move left pointer to the right
// and right pointer to the left
return isPalindromeUtil(s, left + 1, right - 1);
}
static boolean isPalindrome(String s) {
int left = 0;
int right = s.length() - 1;
return isPalindromeUtil(s, left, right);
}
public static void main(String[] args) {
String s = "abba";
System.out.println(isPalindrome(s));
}
}
def isPalindromeUtil(s, left, right):
# Base case
if left >= right:
return True
# If the characters at the current positions are not equal,
# it is not a palindrome
if s[left] != s[right]:
return False
# Move left pointer to the right
# and right pointer to the left
return isPalindromeUtil(s, left + 1, right - 1)
def isPalindrome(s):
left = 0
right = len(s) - 1
return isPalindromeUtil(s, left, right)
s = "abba"
print(isPalindrome(s))
using System;
class GFG {
static bool isPalindromeUtil(string s, int left, int right) {
// Base case
if (left >= right)
return true;
// If the characters at the current positions are
// not equal, it is not a palindrome
if (s[left] != s[right])
return false;
// Move left pointer to the right and right pointer
// to the left
return isPalindromeUtil(s, left + 1, right - 1);
}
public static bool isPalindrome(string s) {
int left = 0;
int right = s.Length - 1;
return isPalindromeUtil(s, left, right);
}
public static void Main() {
string s = "abba";
Console.WriteLine(isPalindrome(s));
}
}
function isPalindromeUtil(s, left, right) {
// Base case
if (left >= right)
return true;
// If the characters at the current positions are not
// equal, return false (not a palindrome)
if (s[left] !== s[right]) {
return false;
}
// Move left pointer to the right and right pointer to
// the left
return isPalindromeUtil(s, left + 1, right - 1);
}
// Function to check if a string is a palindrome
function isPalindrome(s) {
let left = 0;
let right = s.length - 1;
return isPalindromeUtil(s, left, right);
}
// Driver code
let s = "abba";
console.log(isPalindrome(s));
Output
true
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
A palindrome remains the same even after being reversed. So, we can reverse the string and compare it with the original.
- Create the reversed version of the string.
- Compare the reversed string with the original string.
- If both are equal, return
true. - Otherwise, return
false.
#include <bits/stdc++.h>
using namespace std;
bool isPalindrome(string &s) {
// If the reversed string is equal to the given string,
// then it is a palindrome.
return s == string(s.rbegin(), s.rend());
}
int main() {
string s = "abba";
cout << boolalpha << isPalindrome(s) << endl;
return 0;
}
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool isPalindrome(char s[]) {
int length = strlen(s);
char reversed[length + 1];
// Reverse the string
for (int i = 0; i < length; i++) {
reversed[i] = s[length - i - 1];
}
reversed[length] = '\0';
// Check if the reversed string is equal to the original
return strcmp(s, reversed) == 0;
}
int main() {
char s[] = "abba";
printf("%s\n", isPalindrome(s) ? "true" : "false");
return 0;
}
class GFG {
static boolean isPalindrome(String s) {
// If the reversed string is equal to the given string,
// then it is a palindrome.
return s.equals(new StringBuilder(s)
.reverse()
.toString());
}
public static void main(String[] args) {
String s = "abba";
System.out.println(isPalindrome(s));
}
}
def isPalindrome(s):
# If the reversed string is equal to the given string,
# then it is a palindrome.
return s == s[::-1]
s = "abba"
print(isPalindrome(s))
using System;
class GFG {
static bool isPalindrome(string s) {
// If the reversed string is equal to the given string,
// then it is a palindrome.
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
string reversed = new string(charArray);
return s.Equals(reversed);
}
static void Main() {
string s = "abba";
Console.WriteLine(isPalindrome(s));
}
}
function isPalindrome(s) {
// If the reversed string is equal to the given string,
// then it is a palindrome.
const reversed = s.split('').reverse().join('');
return s === reversed;
}
// Driver code
const s = "abba";
console.log(isPalindrome(s));
Output
true
Related Article: