Given a string s, the task is to check if it is palindrome or not.
Example:
Input: s = "abba"
Output: 1
Explanation: s is a palindrome
Input: s = "abc"
Output: 0
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:
C++
#include <bits/stdc++.h>
using namespace std;
// Function to check if a string is a palindrome
int 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 0 (not a palindrome)
if (s[left] != s[right])
return 0;
// Move the left pointer to the right
// and the right pointer to the left
left++;
right--;
}
// If no mismatch is found,
// return 1 (the string is a palindrome)
return 1;
}
int main(){
string s = "abba";
cout << isPalindrome(s) << endl;
return 0;
}
C
#include <stdio.h>
#include <string.h>
// Function to check if a string is a palindrome
int 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 0;
// Move the left pointer to the right and
// the right pointer to the left
left++;
right--;
}
// If no mismatch is found, return 1 (palindrome)
return 1;
}
int main(){
char s[] = "abba";
printf("%d\n", isPalindrome(s));
return 0;
}
Java
class GfG{
// Function to check if a string is a palindrome
public static int 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 0;
// Move the left pointer to the right and
// the right pointer to the left
left++;
right--;
}
// If no mismatch is found, return 1 (palindrome)
return 1;
}
public static void main(String[] args) {
String s = "abba";
System.out.println(isPalindrome(s));
}
}
Python
def is_palindrome(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 0
# Move the left pointer to the right and
# the right pointer to the left
left += 1
right -= 1
# If no mismatch is found, return 1 (palindrome)
return 1
# Driver code
s = "abba"
print(is_palindrome(s))
C#
using System;
class GfG {
// Function to check if a string is a palindrome
static int 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 0;
// Move the left pointer to the right and
// the right pointer to the left
left++;
right--;
}
// If no mismatch is found, return 1 (palindrome)
return 1;
}
static void Main() {
string s = "abba";
Console.WriteLine(IsPalindrome(s));
}
}
JavaScript
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 0;
}
// Move the left pointer to the right and
// the right pointer to the left
left++;
right--;
}
// If no mismatch is found, return 1 (palindrome)
return 1;
}
// Driver code
const s = "abba";
console.log(isPalindrome(s));
Time Complexity: O(n), where n is the length of the input string.
Auxiliary Space: O(1), no extra data structures used.
Optimization of two pointers approach - 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).
C++
#include <bits/stdc++.h>
using namespace std;
// Function to check if a string is a palindrome.
int 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 0 (not a palindrome)
return 0;
}
// If all symmetric characters are equal
// then it is palindrome
return 1;
}
int main(){
string s = "abba";
cout << isPalindrome(s) << endl;
return 0;
}
C
#include <stdio.h>
#include <string.h>
// Function to check if a string is a palindrome
int 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 0 (not a palindrome)
return 0;
}
// If all symmetric characters are equal
// then it is palindrome
return 1;
}
int main() {
char s[] = "abba";
printf("%d\n", isPalindrome(s));
return 0;
}
Java
class GfG {
// Function to check if a string is a palindrome
public static int 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 0 (not a palindrome)
return 0;
}
// If all symmetric characters are equal
// then it is palindrome
return 1;
}
public static void main(String[] args){
String s = "abba";
System.out.println(isPalindrome(s));
}
}
Python
def is_palindrome(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 0 (not a palindrome)
return 0
# If all symmetric characters are equal
# then it is palindrome
return 1
# Driver code
s = "abba"
print(is_palindrome(s))
C#
using System;
class GfG {
// Function to check if a string is a palindrome
static int 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 0 (not a palindrome)
return 0;
}
// If all symmetric characters are equal
// then it is palindrome
return 1;
}
static void Main(){
string s = "abba";
Console.WriteLine(IsPalindrome(s));
}
}
JavaScript
// Function to check if a string is a palindrome.
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 palindrome
return true;
}
// Driver code
let s = "abba";
console.log(isPalindrome(s));
Time Complexity: O(n), where n is the length of the input string.
Auxiliary Space: O(1), no extra data structures used.
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
C++
#include <bits/stdc++.h>
using namespace std;
// Recursive util function to check if a string is a palindrome
int isPalindromeUtil(string & s, int left, int right) {
// Base case
if (left >= right)
return 1;
// If the characters at the current positions are not equal,
// it is not a palindrome
if (s[left] != s[right])
return 0;
// 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
int isPalindrome(string s){
int left = 0, right = s.length() - 1;
return isPalindromeUtil(s, left, right);
}
int main() {
string s = "abba";
cout << isPalindrome(s) << endl;
return 0;
}
C
#include <stdio.h>
#include <string.h>
// Recursive util function to check if a string is a palindrome
int isPalindromeUtil(char *s, int left, int right){
// Base casee
if (left >= right)
return 1;
// If the characters at the current positions are not equal,
// it is not a palindrome
if (s[left] != s[right])
return 0;
// 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
int isPalindrome(char *s){
int left = 0;
int right = strlen(s) - 1;
return isPalindromeUtil(s, left, right);
}
int main(){
char s[] = "abba";
printf("%d\n", isPalindrome(s));
return 0;
}
Java
class GfG {
// Recursive util function to check if a string is a
// palindrome
static int isPalindromeUtil(String s, int left,
int right){
// Base case
if (left >= right)
return 1;
// If the characters at the current positions are
// not equal, it is not a palindrome
if (s.charAt(left) != s.charAt(right))
return 0;
// 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
static int 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));
}
}
Python
def is_palindrome_util(s, left, right):
# Base case
if left >= right:
return 1
# If the characters at the current positions are not equal,
# it is not a palindrome
if s[left] != s[right]:
return 0
# Move left pointer to the right
# and right pointer to the left
return is_palindrome_util(s, left + 1, right - 1)
# Function to check if a string is a palindrome
def is_palindrome(s):
left = 0
right = len(s) - 1
return is_palindrome_util(s, left, right)
# Driver code
s = "abba"
print(is_palindrome(s))
C#
using System;
class GfG {
// Recursive util function to check if a string is a
// palindrome
static int IsPalindromeUtil(string s, int left,
int right){
// Base case
if (left >= right)
return 1;
// If the characters at the current positions are
// not equal, it is not a palindrome
if (s[left] != s[right])
return 0;
// 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
public static int 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));
}
}
JavaScript
function isPalindromeUtil(s, left, right){
// Base case
if (left >= right)
return 1;
// If the characters at the current positions are not
// equal, return 0 (not a palindrome)
if (s[left] !== s[right]) {
return 0;
}
// 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));
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.
C++
#include <bits/stdc++.h>
using namespace std;
// Function to check if a string is a palindrome
int isPalindrome(string & s){
// If reverse string is equal to given string,
// then it is palindrome.
return s == string(s.rbegin(), s.rend()) ? 1 : 0;
}
int main(){
string s = "abba";
cout << isPalindrome(s) << endl;
return 0;
}
C
#include <stdio.h>
#include <string.h>
// Function to check if a string is a palindrome
int 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 ? 1 : 0;
}
int main(){
char s[] = "abba";
printf("%d\n", isPalindrome(s));
return 0;
}
Java
class GfG {
// Function to check if a string is a palindrome
static int isPalindrome(String s){
// If reverse string is equal to given string,
// then it is palindrome.
return s.equals(new StringBuilder(s)
.reverse()
.toString() ? 1 : 0;
}
public static void main(String[] args){
String s = "abba";
System.out.println(isPalindrome(s));
}
}
Python
def is_palindrome(s):
#If reverse string is equal to given string,
# then it is palindrome.
return 1 if s == s[::-1] else 0
# Driver code
s = "abba"
print(is_palindrome(s))
C#
using System;
class GfG{
// Function to check if a string is a palindrome
static int IsPalindrome(string s) {
// If reverse string is equal to given string,
// then it is palindrome.
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
string reversed = new string(charArray);
return s.Equals(reversed) ? 1 : 0;
}
static void Main() {
string s = "abba";
Console.WriteLine(IsPalindrome(s));
}
}
JavaScript
function isPalindrome(s) {
// If reverse string is equal to given string,
// then it is palindrome.
const reversed = s.split('').reverse().join('');
return s === reversed ? 1 : 0;
}
// Driver code
const s = "abba";
console.log(isPalindrome(s));
Time Complexity: O(n), where n is the length of the input string.
Auxiliary Space: O(n), for creating another string
Related Article:
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem