Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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:
Check if there exist a string Y such that (X+Y) and (Y+X) are palindromes
Next article icon

Check if there exists any sub-sequence in a string which is not palindrome

Last Updated : 07 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string s consisting of lowercase characters, the task is to check if there exists any subsequence in the string which is not a palindrome. If there is at least 1 such subsequence, then return true, otherwise return false.

Examples: 

Input : str = “abaab”
Output: Yes
Explanation: Subsequences “ab” , “abaa” , “aab”, are not a palindrome.

Input : str = “zzzz”
Output: NO
Explanation: All possible subsequences are palindrome.

[Naive Approach] Checking Each Subsequence – O(2^n) time and O(n) space

The idea is to generate all possible subsequences of the given string and check each one to see if it’s not a palindrome. If we find even one subsequence that is not a palindrome, we return true; otherwise, we return false.

C++
// C++ program to Check if there exists any subsequence // in a string which is not palindrome #include <bits/stdc++.h> using namespace std;  // Function to check if a string is  // palindrome or not. bool isPalindrome(string s) {          // Empty string is also palindrom     if (s.length() == 0) return true;          int left = 0, right = s.length() - 1;     while (left < right) {         if (s[left] != s[right])             return false;         left++;         right--;     }     return true; }  bool generateSubsequences(string s, int i, string curr) {     if (i == s.length()) {         return isPalindrome(curr) == false;     }          // Take current character     bool take = generateSubsequences(s, i + 1, curr + s[i]);          // Skip current character     bool noTake = generateSubsequences(s, i + 1, curr);          return take || noTake; }  bool notPalindromeSub(string s) {     return generateSubsequences(s, 0, ""); }  int main() {     string s = "abaab";     if (notPalindromeSub(s)) {         cout << "Yes" << endl;     }     else {         cout << "No" << endl;     }     return 0; } 
Java
// Java program to Check if there exists any subsequence // in a string which is not palindrome  class GfG {      // Function to check if a string is      // palindrome or not.     static boolean isPalindrome(String s) {         if (s.length() == 0) return true;         int left = 0, right = s.length() - 1;         while (left < right) {             if (s.charAt(left) != s.charAt(right))                 return false;             left++;             right--;         }         return true;     }      static boolean generateSubsequences(String s, int i, String curr) {         if (i == s.length()) {             return isPalindrome(curr) == false;         }          // Take current character         boolean take = generateSubsequences(s, i + 1, curr + s.charAt(i));          // Skip current character         boolean noTake = generateSubsequences(s, i + 1, curr);          return take || noTake;     }      static boolean notPalindromeSub(String s) {         return generateSubsequences(s, 0, "");     }      public static void main(String[] args) {         String s = "abaab";         if (notPalindromeSub(s)) {             System.out.println("Yes");         } else {             System.out.println("No");         }     } } 
Python
# Python program to Check if there exists any subsequence # in a string which is not palindrome  # Function to check if a string is  # palindrome or not. def isPalindrome(s):     if len(s) == 0:         return True     left = 0     right = len(s) - 1     while left < right:         if s[left] != s[right]:             return False         left += 1         right -= 1     return True  def generateSubsequences(s, i, curr):     if i == len(s):         return isPalindrome(curr) == False      # Take current character     take = generateSubsequences(s, i + 1, curr + s[i])      # Skip current character     noTake = generateSubsequences(s, i + 1, curr)      return take or noTake  def notPalindromeSub(s):     return generateSubsequences(s, 0, "")  if __name__ == "__main__":     s = "abaab"     if notPalindromeSub(s):         print("Yes")     else:         print("No") 
C#
// C# program to Check if there exists any subsequence // in a string which is not palindrome  using System;  class GfG {      // Function to check if a string is      // palindrome or not.     static bool isPalindrome(string s) {         if (s.Length == 0) return true;         int left = 0, right = s.Length - 1;         while (left < right) {             if (s[left] != s[right])                 return false;             left++;             right--;         }         return true;     }      static bool generateSubsequences(string s, int i, string curr) {         if (i == s.Length) {             return isPalindrome(curr) == false;         }          // Take current character         bool take = generateSubsequences(s, i + 1, curr + s[i]);          // Skip current character         bool noTake = generateSubsequences(s, i + 1, curr);          return take || noTake;     }      static bool notPalindromeSub(string s) {         return generateSubsequences(s, 0, "");     }      static void Main(string[] args) {         string s = "abaab";         if (notPalindromeSub(s)) {             Console.WriteLine("Yes");         } else {             Console.WriteLine("No");         }     } } 
JavaScript
// JavaScript program to Check if there exists any subsequence // in a string which is not palindrome  // Function to check if a string is  // palindrome or not. function isPalindrome(s) {     if (s.length === 0) return true;     let left = 0, right = s.length - 1;     while (left < right) {         if (s[left] !== s[right])             return false;         left++;         right--;     }     return true; }  function generateSubsequences(s, i, curr) {     if (i === s.length) {         return isPalindrome(curr) === false;     }      // Take current character     let take = generateSubsequences(s, i + 1, curr + s[i]);      // Skip current character     let noTake = generateSubsequences(s, i + 1, curr);      return take || noTake; }  function notPalindromeSub(s) {     return generateSubsequences(s, 0, ""); }  let s = "abaab"; if (notPalindromeSub(s)) {     console.log("Yes"); } else {     console.log("No"); } 

Output
Yes 

[Expected Approach] Using Hash Set – O(n) time and O(1) space

The idea is to recognize that a subsequence is not a palindrome if and only if the string contains at least two different characters. This is because any subsequence with all same characters is always a palindrome, and any subsequence with at least two different characters can be arranged to form a non-palindrome.

Step by step approach:

  1. Create a hash set to store unique characters.
  2. Iterate through each character of the string and add each character to the hash set.
  3. If the hash set size is >= 2, return true (found a non-palindrome subsequence). Otherwise, return false.
C++
// C++ program to Check if there exists any subsequence // in a string which is not palindrome #include <bits/stdc++.h> using namespace std;  bool notPalindromeSub(string s) {     unordered_set<char> set;          for (char c : s) {         set.insert(c);     }          // If there are at least 2 different characters,     // we can form a non-palindrome subsequence     return set.size() >= 2; }  int main() {     string s = "abaab";     if (notPalindromeSub(s)) {         cout << "Yes" << endl;     }     else {         cout << "No" << endl;     }     return 0; } 
Java
// Java program to Check if there exists any subsequence // in a string which is not palindrome  import java.util.*;  class GfG {      static boolean notPalindromeSub(String s) {         HashSet<Character> set = new HashSet<>();          for (int i = 0; i < s.length(); i++) {             set.add(s.charAt(i));         }          // If there are at least 2 different characters,         // we can form a non-palindrome subsequence         return set.size() >= 2;     }      public static void main(String[] args) {         String s = "abaab";         if (notPalindromeSub(s)) {             System.out.println("Yes");         } else {             System.out.println("No");         }     } } 
Python
# Python program to Check if there exists any subsequence # in a string which is not palindrome  def notPalindromeSub(s):     setChars = set()      for c in s:         setChars.add(c)      # If there are at least 2 different characters,     # we can form a non-palindrome subsequence     return len(setChars) >= 2  if __name__ == "__main__":     s = "abaab"     if notPalindromeSub(s):         print("Yes")     else:         print("No") 
C#
// C# program to Check if there exists any subsequence // in a string which is not palindrome  using System; using System.Collections.Generic;  class GfG {      static bool notPalindromeSub(string s) {         HashSet<char> set = new HashSet<char>();          foreach (char c in s) {             set.Add(c);         }          // If there are at least 2 different characters,         // we can form a non-palindrome subsequence         return set.Count >= 2;     }      static void Main(string[] args) {         string s = "abaab";         if (notPalindromeSub(s)) {             Console.WriteLine("Yes");         } else {             Console.WriteLine("No");         }     } } 
JavaScript
// JavaScript program to Check if there exists any subsequence // in a string which is not palindrome  function notPalindromeSub(s) {     let set = new Set();      for (let i = 0; i < s.length; i++) {         set.add(s[i]);     }      // If there are at least 2 different characters,     // we can form a non-palindrome subsequence     return set.size >= 2; }  let s = "abaab"; if (notPalindromeSub(s)) {     console.log("Yes"); } else {     console.log("No"); } 

Output
Yes 


Next Article
Check if there exist a string Y such that (X+Y) and (Y+X) are palindromes

S

souradeep
Improve
Article Tags :
  • Data Structures
  • DSA
  • Strings
  • palindrome
  • subsequence
Practice Tags :
  • Data Structures
  • palindrome
  • Strings

Similar Reads

  • Check if two same sub-sequences exist in a string or not
    Given a string, the task is to check if there exist two equal sub-sequences in the given string. Two sub-sequences are said to be equal if they have the same characters arranged in the same lexicographical order but the position of characters differs from that in the original string. Examples: Input
    5 min read
  • Check if a number is palindrome or not without using any extra space | Set 2
    Given a number ‘n’ and our goal is to find out it is palindrome or not without using any extra space. We can’t make a new copy of number. Examples: Input: n = 2332Output: Yes it is Palindrome.Explanation:original number = 2332reversed number = 2332Both are same hence the number is palindrome. Input:
    5 min read
  • Given two strings check which string makes a palindrome first
    Given two strings 'A' and 'B' of equal length. Two players play a game where they both pick a character from their respective strings (First picks from A and second from B) and put into a third string (which is initially empty). The player that can make the third string palindrome, is winner. If fir
    6 min read
  • Check if the characters in a string form a Palindrome in O(1) extra space
    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
    10 min read
  • Check if there exist a string Y such that (X+Y) and (Y+X) are palindromes
    Given a string X of length N and an integer K, the task is to determine if there exists a string (say Y) of length K such that its concatenation on either side of X makes the resultant string palindrome i.e. X+Y and Y+X both are palindromes. Examples: Input: N = 6, K = 2, X = "abbaab"Output: YesExpl
    10 min read
  • Queries to check if the path between two nodes in a tree is a palindrome
    Given a tree with N nodes and N - 1 edges. Each edge of the tree is labeled by a string of lowercase english alphabets. You are given Q queries. In each query you are given two node x and y. For the path between x to y, the task is to check if it is possible to make a new palindrome string which use
    15+ min read
  • Check if all the palindromic sub-strings are of odd length
    Given a string 's' check if all of its palindromic sub-strings are of odd length or not. If yes then print "YES" or "NO" otherwise. Examples: Input: str = "geeksforgeeks" Output: NO Since, "ee" is a palindromic sub-string of even length. Input: str = "madamimadam" Output: YES Brute Force Approach: S
    10 min read
  • Check if a linked list of strings forms a palindrome
    Given a linked list handling string data, check to see whether data is palindrome or not? For example, Input : a -> bc -> d -> dcb -> a -> NULL Output : True String "abcddcba" is palindrome. Output : a -> bc -> d -> ba -> NULL Output : False String "abcdba" is not palindro
    6 min read
  • To check a number is palindrome or not without using any extra space
    Given a number 'n' and our goal is to find out it is palindrome or not without using any extra space. We can't make a new copy of the number . Examples: Input : 2332 Output : Yes it is Palindrome. Explanation: original number = 2332 reversed number = 2332 Both are same hence the number is palindrome
    6 min read
  • Check if there exists a permutation of given string which doesn't contain any monotonous substring
    Given a string S of lowercase English alphabets, the task is to check if there exists an arrangement of string S such that it doesn't contain any monotonous substring. A monotonous substring has the following properties: Length of such substring is 2.Both the characters are consecutive, For example
    7 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