Check if the characters in a string form a Palindrome in O(1) extra space - GeeksforGeeks

09 Nov, 2021
Given string str. The string may contain lower-case letters, special characters, digits, or even white spaces. The task is to check whether only the letters present in the string are forming a Palindromic combination or not without using any extra space.Note: It is not allowed to use extra space to solve this problem. Also, the letters present in the string are in lower-case and the string may contain special characters, digits, or even white spaces along with lowercase letters.
Examples: 
Input : str = “m a 343 la y a l am” Output : YES The characters in the string form the sequence “malayalam”, which is a palindrome.
Input : str = “malayalam” Output : YES
Approach:
Create two utility functions to get the first and last position of characters present in the string.
Start traversing the string, and keep finding the position of the first and last characters every time.
If the first and last characters are the same for every iteration and the string is traversed completely, then print YES, otherwise print NO.
Below is the implementation of the above approach: 
C++
Java
Python 3
C#
PHP
Javascript
// CPP program to check if the characters in// the given string forms a Palindrome in// O(1) extra space#include <iostream>using namespace std; // Utility function to get the position of// first character in the stringint firstPos(string str, int start, int end){    int firstChar = -1;     // Get the position of first character    // in the string    for (int i = start; i <= end; i++) {        if (str[i] >= 'a' && str[i] <= 'z') {            firstChar = i;            break;        }    }     return firstChar;} // Utility function to get the position of// last character in the stringint lastPos(string str, int start, int end){    int lastChar = -1;     // Get the position of last character    // in the string    for (int i = start; i >= end; i--) {        if (str[i] >= 'a' && str[i] <= 'z') {            lastChar = i;            break;        }    }     return lastChar;} // Function to check if the characters in// the given string forms a Palindrome in// O(1) extra spacebool isPalindrome(string str){    int firstChar = 0, lastChar = str.length() - 1;    bool ch = true;     for (int i = 0; i < str.length(); i++) {        firstChar = firstPos(str, firstChar, lastChar);        lastChar = lastPos(str, lastChar, firstChar);         // break, when all letters are checked        if (lastChar < 0 || firstChar < 0)            break;        if (str[firstChar] == str[lastChar]) {            firstChar++;            lastChar--;            continue;        }         // if mismatch found, break the loop        ch = false;        break;    }     return (ch);} // Driver codeint main(){    string str = "m     a  343 la y a l am";    if (isPalindrome(str))        cout << "YES";    else        cout << "NO";     return 0;}
// Java program to check if// the characters in the given// string forms a Palindrome// in O(1) extra spaceimport java.io.*; class GFG{ // Utility function to get// the position of first// character in the stringstatic int firstPos(String str,                    int start,                    int end){    int firstChar = -1;         // Get the position of    // first character in    // the string    for(int i = start; i <= end; i++)    {        if(str.charAt(i) >= 'a'&&        str.charAt(i) <= 'z')        {            firstChar = i;            break;        }    }         return firstChar;} // Utility function to get// the position of last// character in the stringstatic int lastPos(String str,                int start,                int end){    int lastChar = -1;         // Get the position of last    // character in the string    for(int i = start; i >= end; i--)    {        if(str.charAt(i) >= 'a'&&        str.charAt(i) <= 'z')        {            lastChar = i;            break;        }    }         return lastChar;} // Function to check if the// characters in the given// string forms a Palindrome// in O(1) extra spacestatic boolean isPalindrome(String str){    int firstChar = 0,        lastChar = str.length() - 1;    boolean ch = true;     for (int i = 0; i < str.length(); i++)    {        firstChar = firstPos(str, firstChar,                                lastChar);        lastChar = lastPos(str, lastChar,                                firstChar);         // break, when all        // letters are checked        if (lastChar < 0 || firstChar < 0)            break;        if (str.charAt(firstChar) ==            str.charAt(lastChar))        {            firstChar++;            lastChar--;            continue;        }                 // if mismatch found,        // break the loop        ch = false;        break;    }         return ch; } // Driver codepublic static void main (String[] args){    String str = "m a 343 la y a l am";         if(isPalindrome(str))        System.out.print("YES");    else    System.out.println("NO");}} // This code is contributed// by inder_verma.
# Python 3 program to check if the characters# in the given string forms a Palindrome in# O(1) extra space # Utility function to get the position of# first character in the stringdef firstPos(str, start, end):     firstChar = -1     # Get the position of first character    # in the string    for i in range(start, end + 1):        if (str[i] >= 'a' and str[i] <= 'z') :            firstChar = i            break     return firstChar # Utility function to get the position of# last character in the stringdef lastPos(str, start, end):     lastChar = -1     # Get the position of last character    # in the string    for i in range(start, end - 1, -1) :        if (str[i] >= 'a' and str[i] <= 'z') :            lastChar = i            break     return lastChar # Function to check if the characters in# the given string forms a Palindrome in# O(1) extra spacedef isPalindrome(str):     firstChar = 0    lastChar = len(str) - 1    ch = True     for i in range(len(str)) :        firstChar = firstPos(str, firstChar, lastChar);        lastChar = lastPos(str, lastChar, firstChar);         # break, when all letters are checked        if (lastChar < 0 or firstChar < 0):            break        if (str[firstChar] == str[lastChar]):            firstChar += 1            lastChar -= 1            continue         # if mismatch found, break the loop        ch = False        break     return (ch) # Driver codeif __name__ == "__main__":         str = "m     a 343 la y a l am"    if (isPalindrome(str)):        print("YES")    else:        print("NO") # This code is contributed by ita_c
// C# program to check if// the characters in the given// string forms a Palindrome// in O(1) extra spaceusing System; class GFG{ // Utility function to get// the position of first// character in the stringstatic int firstPos(string str,                    int start,                    int end){    int firstChar = -1;         // Get the position of    // first character in    // the string    for(int i = start; i <= end; i++)    {        if(str[i] >= 'a'&&           str[i] <= 'z')        {            firstChar = i;            break;        }    }         return firstChar;} // Utility function to get// the position of last// character in the stringstatic int lastPos(string str,                   int start,                   int end){    int lastChar = -1;         // Get the position of last    // character in the string    for(int i = start; i >= end; i--)    {        if(str[i] >= 'a'&&           str[i] <= 'z')        {            lastChar = i;            break;        }    }         return lastChar;} // Function to check if the// characters in the given// string forms a Palindrome// in O(1) extra spacestatic bool isPalindrome(string str){    int firstChar = 0,        lastChar = str.Length - 1;    bool ch = true;     for (int i = 0; i < str.Length; i++)    {        firstChar = firstPos(str, firstChar,                                  lastChar);        lastChar = lastPos(str, lastChar,                                firstChar);         // break, when all        // letters are checked        if (lastChar < 0 || firstChar < 0)            break;        if (str[firstChar] ==            str[lastChar])        {            firstChar++;            lastChar--;            continue;        }                 // if mismatch found,        // break the loop        ch = false;        break;    }         return ch;} // Driver codepublic static void Main (){    string str = "m a 343 la y a l am";         if(isPalindrome(str))        Console.WriteLine("YES");    else        Console.WriteLine("NO");}} // This code is contributed// by inder_verma.
<?php// PHP program to check if the// characters in the given// string forms a Palindrome// in O(1) extra space // Utility function to get the// position of first character// in the stringfunction firstPos($str, $start, $end){    $firstChar = -1;     // Get the position of first    // character in the string    for ($i = $start; $i <= $end; $i++)    {        if ($str[$i] >= 'a' and            $str[$i] <= 'z')        {            $firstChar = $i;            break;        }    }     return $firstChar;} // Utility function to get the// position of last character// in the stringfunction lastPos($str, $start, $end){    $lastChar = -1;     // Get the position of last    // character in the string    for ( $i = $start; $i >= $end; $i--)    {        if ($str[$i] >= 'a' and            $str[$i] <= 'z')        {            $lastChar = $i;            break;        }    }     return $lastChar;} // Function to check if the// characters in the given// string forms a Palindrome// in O(1) extra spacefunction isPalindrome($str){    $firstChar = 0;    $lastChar = count($str) - 1;    $ch = true;     for ($i = 0; $i < count($str); $i++)    {        $firstChar = firstPos($str, $firstChar,                                    $lastChar);        $lastChar = lastPos($str, $lastChar,                                  $firstChar);         // break, when all letters are checked        if ($lastChar < 0 or $firstChar < 0)            break;        if ($str[$firstChar] == $str[$lastChar])        {            $firstChar++;            $lastChar--;            continue;        }         // if mismatch found,        // break the loop        $ch = false;        break;    }     return ($ch);} // Driver code$str = "m a 343 la y a l am";if (isPalindrome($str))    echo "YES";else    echo "NO"; // This code is contributed// by inder_verma.?>
<script>// Javascript program to check if// the characters in the given// string forms a Palindrome// in O(1) extra space // Utility function to get// the position of first// character in the stringfunction firstPos(str,start,end){    let firstChar = -1;           // Get the position of    // first character in    // the string    for(let i = start; i <= end; i++)    {        if(str[i] >= 'a'&&        str[i] <= 'z')        {            firstChar = i;            break;        }    }           return firstChar;} // Utility function to get// the position of last// character in the stringfunction lastPos(str,start,end){    let lastChar = -1;           // Get the position of last    // character in the string    for(let i = start; i >= end; i--)    {        if(str[i] >= 'a'&&        str[i] <= 'z')        {            lastChar = i;            break;        }    }           return lastChar;}    // Function to check if the// characters in the given// string forms a Palindrome// in O(1) extra spacefunction isPalindrome(str){    let firstChar = 0,        lastChar = str.length - 1;    let ch = true;       for (let i = 0; i < str.length; i++)    {        firstChar = firstPos(str, firstChar,                                lastChar);        lastChar = lastPos(str, lastChar,                                firstChar);           // break, when all        // letters are checked        if (lastChar < 0 || firstChar < 0)            break;        if (str[firstChar] ==            str[lastChar])        {            firstChar++;            lastChar--;            continue;        }                   // if mismatch found,        // break the loop        ch = false;        break;    }           return ch;} // Driver codelet str = "m a 343 la y a l am";if(isPalindrome(str))    document.write("YES");else    document.write("NO");       // This code is contributed by avanitrachhadiya2155</script>
YES
 
inderDuMCA
ukasp
avanitrachhadiya2155
gabaa406
surinderdawra388
C-String-Question
palindrome
Strings
Strings
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check for Balanced Brackets in an expression (well-formedness) using Stack
KMP Algorithm for Pattern Searching
Convert string to char array in C++
Longest Palindromic Substring | Set 1
Array of Strings in C++ (5 Different Ways to Create)
Caesar Cipher in Cryptography
Check whether two strings are anagram of each other
Top 50 String Coding Problems for Interviews
Length of the longest substring without repeating characters
How to split a string in C/C++, Python and Java?