Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Print longest palindrome word in a sentence
Next article icon

Sentence Palindrome

Last Updated : 12 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given a sentence s, the task is to check if it is a palindrome sentence or not. A palindrome sentence is a sequence of characters, such as a word, phrase, or series of symbols, that reads the same backward as forward after converting all uppercase letters to lowercase and removing all non-alphanumeric characters.

Examples: 

Input: s = "Too hot to hoot."
Output: True
Explanation: If we remove all non-alphanumeric characters and convert all uppercase letters to lowercase, string s will become "toohottohoot" which is a palindrome.

Input: s = "Abc 012..## 10cbA"
Output: True
Explanation: If we remove all non-alphanumeric characters and convert all uppercase letters to lowercase, string s will become "abc01210cba" which is a palindrome.

Input: s = "ABC $. def01ASDF.."
Output: False
Explanation: If we remove all non-alphanumeric characters and convert all uppercase letters to lowercase, string s will become "abcdef01asdf" which is not a palindrome.

Table of Content

  • [Naive Approach] Comparing original and reversed strings - O(n) Time and O(n) Space
  • [Expected Approach] Using Two Pointers - O(n) Time and O(1) Space

[Naive Approach] Comparing original and reversed strings - O(n) Time and O(n) Space

A simple approach is to create a new string containing only the alphanumeric characters of the original string. Also, in case of uppercase letters convert them to lowercase. Then, compare this new string with its reverse to know if the sentence is a palindromic sentence or not.

C++
// C++ program to check string for palindrome // by comparing original and reversed strings  #include <algorithm> #include <iostream> using namespace std;  bool sentencePalindrome(string &s) {      // create a new string having only     // alphanumeric characters     string s1 = "";     for (char ch : s) {         if (isalnum(ch)) {             s1.push_back(tolower(ch));         }     }      // find reverse of this new string     string rev = s1;     reverse(rev.begin(), rev.end());      // compare string and its reverse     return s1 == rev; }  int main() {     string s = "Too hot to hoot.";      cout << (sentencePalindrome(s) ? "True" : "False") << endl;     return 0; } 
Java
// Java program to check string for palindrome by comparing  // original and reversed strings  import java.util.*;  class GfG {      static boolean sentencePalindrome(String s) {            // create a new string having only          // alphanumeric characters         StringBuilder s1 = new StringBuilder();         for (char ch : s.toCharArray()) {             if (Character.isLetterOrDigit(ch)) {                 s1.append(Character.toLowerCase(ch));             }         }            // find reverse of this new string         StringBuilder rev = new StringBuilder(s1.toString());         rev.reverse();            // compare string and its reverse         return s1.toString().equals(rev.toString());     }      public static void main(String[] args) {         String s = "Too hot to hoot.";            System.out.println(sentencePalindrome(s)                            			? "True" : "False");     } } 
Python
# Python program to check string for palindrome  # by comparing original and reversed strings  def sentencePalindrome(s):        # create a new list having only      # alphanumeric characters     s1 = []     for ch in s:         if ch.isalnum():             s1.append(ch.lower()) 	     # Convert the new list to string     s1 = ''.join(s1)          # find reverse of this new string     rev = s1[::-1]          # compare string and its reverse     return s1 == rev  if __name__ == "__main__":     s = "Too hot to hoot."     print("True" if sentencePalindrome(s) else "False") 
C#
// C# program to check string for palindrome  // by comparing original and reversed strings  using System; using System.Text; using System.Linq;  class GfG {          // Function to check if the sentence is a palindrome     static bool sentencePalindrome(ref string s) {         StringBuilder s1 = new StringBuilder();                  // Filter out non-alphanumeric characters and          // convert to lowercase         foreach (char ch in s) {             if (Char.IsLetterOrDigit(ch))                  s1.Append(Char.ToLower(ch));         }                  string s2 = s1.ToString();          		// find reverse of this new string     	char[] revArray = s2.ToCharArray().Reverse().ToArray();     	string rev = new string(revArray);   	   		// compare string and its reverse     	return s2 == rev;     }      static void Main() {         string s = "Too hot to hoot.";         Console.WriteLine(sentencePalindrome(ref s) ? "True" : "False");     } } 
JavaScript
// JavaScript program to check string for palindrome // by comparing original and reversed strings  function sentencePalindrome(s) {      // create an array to store only alphanumeric characters     let s1 = [];     for (let i = 0; i < s.length; i++) {         let ch = s[i];          // Check if the character is alphanumeric         if (/[a-zA-Z0-9]/.test(ch)) {             s1.push(ch.toLowerCase());         }     }      // find reverse of this new string by joining the array     // into a string     let rev = s1.slice().reverse().join("");      // compare string and its reverse     return s1.join("") === rev; }  let s = "Too hot to hoot.";  console.log(sentencePalindrome(s) ? "True" : "False"); 

Output
True 

[Expected Approach] Using Two Pointers - O(n) Time and O(1) Space

The idea is to use two pointers approach to find if a sentence is palindrome or not. Maintain one pointer at the beginning and the other at the end of the sentence. The pointers move towards each other, comparing characters along the way. If the characters match, we continue moving both pointers inward; if they differ, we return false, indicating the sentence is not a palindrome.

Also, while comparing we skip all non-alphanumeric characters. Finally, if the pointers cross each other, this means that the sentence is a palindrome.


C++
// C++ program to find if a sentence is // palindrome using two pointers #include <iostream> using namespace std;  // To check sentence is palindrome or not bool sentencePalindrome(string s) {     int i = 0, j = s.length() - 1;      // Compares character until they are equal     while (i < j) {          // Skip non alphabet character         // from left side         if (!isalnum(s[i]))             i++;          // Skip non alphabet character         // from right side         else if (!isalnum(s[j]))             j--;          // If characters are equal         // update the pointers         else if (tolower(s[i]) == tolower(s[j]))             i++, j--;          // If characters are not equal then         // sentence is not palindrome         else             return false;     }      // Return true as sentence is palindrome     return true; }  int main() {     string s = "Too hot to hoot.";      cout << (sentencePalindrome(s) ? "True" : "False") << endl;     return 0; } 
C
// C program to find if a sentence is // palindrome using two pointers #include <stdio.h> #include <stdbool.h>  // To check sentence is palindrome or not bool sentencePalindrome(const char* s) {     int i = 0, j = strlen(s) - 1;      // Compares character until they are equal     while (i < j) {          // Skip non alphabet character         // from left side         if (!isalnum(s[i]))             i++;          // Skip non alphabet character         // from right side         else if (!isalnum(s[j]))             j--;          // If characters are equal          // update the pointers         else if (tolower(s[i]) == tolower(s[j]))             i++, j--;          // If characters are not equal then         // sentence is not palindrome         else             return false;     }      // Return true as sentence is palindrome     return true; }  int main() {     const char* s = "Too hot to hoot.";      printf("%s\n", sentencePalindrome(s) ? "True" : "False");     return 0; } 
Java
// Java program to find if a sentence is // palindrome using two pointers class GfG {      // To check sentence is palindrome or not     static boolean sentencePalindrome(String s) {         int i = 0, j = s.length() - 1;          // Compares character until they are equal         while (i < j) {              // Skip non alphabet character from left side             if (!Character.isLetterOrDigit(s.charAt(i)))                 i++;              // Skip non alphabet character from right side             else if (!Character.isLetterOrDigit(s.charAt(j)))                 j--;              // If characters are equal update the pointers             else if (Character.toLowerCase(s.charAt(i))                      == Character.toLowerCase(s.charAt(j))) {                 i++;                 j--;             }                        // If characters are not equal then sentence             // is not palindrome             else                 return false;         }          // Return true as sentence is palindrome         return true;     }      public static void main(String[] args) {         String s = "Too hot to hoot.";          System.out.println(sentencePalindrome(s)                             ? "True" : "False");     } } 
Python
# Python program to find if a sentence is # palindrome using two pointers  # To check sentence is palindrome or not def sentencePalindrome(s):     i, j = 0, len(s) - 1      # Compares character until they are equal     while i < j:          # Skip non alphabet character         # from left side         if not s[i].isalnum():             i += 1          # Skip non alphabet character         # from right side         elif not s[j].isalnum():             j -= 1          # If characters are equal          # update the pointers         elif s[i].lower() == s[j].lower():             i += 1             j -= 1          # If characters are not equal then         # sentence is not palindrome         else:             return False      # Return true as sentence is palindrome     return True  if __name__ == "__main__":     s = "Too hot to hoot."      print("True" if sentencePalindrome(s) else "False") 
C#
// C# program to find if a sentence is // palindrome using two pointers using System;  class GfG {      // To check sentence is palindrome or not     static bool sentencePalindrome(string s) {         int i = 0, j = s.Length - 1;          // Compares character until they are equal         while (i < j) {              // Skip non alphabet character             // from left side             if (!char.IsLetterOrDigit(s[i]))                 i++;              // Skip non alphabet character             // from right side             else if (!char.IsLetterOrDigit(s[j]))                 j--;              // If characters are equal              // update the pointers             else if (char.ToLower(s[i]) == char.ToLower(s[j])) {                 i++;                 j--;             }              // If characters are not equal then             // sentence is not palindrome             else                 return false;         }          // Return true as sentence is palindrome         return true;     }      static void Main() {         string s = "Too hot to hoot.";          Console.WriteLine(sentencePalindrome(s) ? "True" : "False");     } } 
JavaScript
// JavaScript program to find if a sentence is // palindrome using two pointers  // To check sentence is palindrome or not function sentencePalindrome(s) {     let i = 0, j = s.length - 1;      // Compares character until they are equal     while (i < j) {          // Skip non alphabet character         // from left side         if (!s[i].match(/[a-zA-Z0-9]/))             i++;          // Skip non alphabet character         // from right side         else if (!s[j].match(/[a-zA-Z0-9]/))             j--;          // If characters are equal         // update the pointers         else if (s[i].toLowerCase() === s[j].toLowerCase())             i++, j--;          // If characters are not equal then         // sentence is not palindrome         else             return false;     }      // Return true as sentence is palindrome     return true; }  // Driver Code let s = "Too hot to hoot."; console.log(sentencePalindrome(s) ? "True" : "False"); 

Output
True 



Next Article
Print longest palindrome word in a sentence

N

nuclode
Improve
Article Tags :
  • Strings
  • DSA
  • palindrome
Practice Tags :
  • palindrome
  • Strings

Similar Reads

    Palindrome String Coding Problems
    A string is called a palindrome if the reverse of the string is the same as the original one.Example: “madam”, “racecar”, “12321”.Palindrome StringProperties of a Palindrome String:A palindrome string has some properties which are mentioned below:A palindrome string has a symmetric structure which m
    2 min read
    Palindrome String
    Given a string s, the task is to check if it is palindrome or not.Example:Input: s = "abba"Output: 1Explanation: s is a palindromeInput: s = "abc" Output: 0Explanation: s is not a palindromeUsing Two-Pointers - O(n) time and O(1) spaceThe idea is to keep two pointers, one at the beginning (left) and
    13 min read

    Check Palindrome by Different Language

    Program to Check Palindrome Number in C
    Palindrome numbers are those numbers that remain the same even after reversing the order of their digits. In this article, we will learn how to check whether the given number is a palindrome number using C program.ExamplesInput: 121Output: YesExplanation: The number 121 remains the same when its dig
    3 min read
    C Program to Check for Palindrome String
    A string is said to be palindrome if the reverse of the string is the same as the string. In this article, we will learn how to check whether the given string is palindrome or not using C program.The simplest method to check for palindrome string is to reverse the given string and store it in a temp
    4 min read
    C++ Program to Check if a Given String is Palindrome or Not
    A string is said to be palindrome if the reverse of the string is the same as the original string. In this article, we will check whether the given string is palindrome or not in C++.ExamplesInput: str = "ABCDCBA"Output: "ABCDCBA" is palindromeExplanation: Reverse of the string str is "ABCDCBA". So,
    4 min read
    Java Program to Check Whether a String is a Palindrome
    A string in Java can be called a palindrome if we read it from forward or backward, it appears the same or in other words, we can say if we reverse a string and it is identical to the original string for example we have a string s = "jahaj " and when we reverse it s = "jahaj"(reversed) so they look
    8 min read

    Easy Problems on Palindrome

    Sentence Palindrome
    Given a sentence s, the task is to check if it is a palindrome sentence or not. A palindrome sentence is a sequence of characters, such as a word, phrase, or series of symbols, that reads the same backward as forward after converting all uppercase letters to lowercase and removing all non-alphanumer
    9 min read
    Check if actual binary representation of a number is palindrome
    Given a non-negative integer n. The problem is to check if binary representation of n is palindrome or not. Note that the actual binary representation of the number is being considered for palindrome checking, no leading 0’s are being considered. Examples : Input : 9 Output : Yes (9)10 = (1001)2 Inp
    6 min read
    Print longest palindrome word in a sentence
    Given a string str, the task is to print longest palindrome word present in the string str.Examples: Input : Madam Arora teaches Malayalam Output: Malayalam Explanation: The string contains three palindrome words (i.e., Madam, Arora, Malayalam) but the length of Malayalam is greater than the other t
    14 min read
    Count palindrome words in a sentence
    Given a string str and the task is to count palindrome words present in the string str. Examples: Input : Madam Arora teaches malayalam Output : 3 The string contains three palindrome words (i.e., Madam, Arora, malayalam) so the count is three. Input : Nitin speaks malayalam Output : 2 The string co
    5 min read
    Check if characters of a given string can be rearranged to form a palindrome
    Given a string, Check if the characters of the given string can be rearranged to form a palindrome. For example characters of "geeksogeeks" can be rearranged to form a palindrome "geeksoskeeg", but characters of "geeksforgeeks" cannot be rearranged to form a palindrome. Recommended PracticeAnagram P
    14 min read
    Lexicographically first palindromic string
    Rearrange the characters of the given string to form a lexicographically first palindromic string. If no such string exists display message "no palindromic string". Examples: Input : malayalam Output : aalmymlaa Input : apple Output : no palindromic string Simple Approach: 1. Sort the string charact
    13 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences